diff --git a/dist/image-sequencer.js b/dist/image-sequencer.js
index 2b945b54..a3cd0f61 100644
--- a/dist/image-sequencer.js
+++ b/dist/image-sequencer.js
@@ -9751,9821 +9751,2731 @@ function isSlowBuffer (obj) {
},{}],48:[function(require,module,exports){
arguments[4][8][0].apply(exports,arguments)
},{"dup":8}],49:[function(require,module,exports){
-/*!
- * jQuery JavaScript Library v2.2.4
- * http://jquery.com/
- *
- * Includes Sizzle.js
- * http://sizzlejs.com/
- *
- * Copyright jQuery Foundation and other contributors
- * Released under the MIT license
- * http://jquery.org/license
- *
- * Date: 2016-05-20T17:23Z
- */
-
-(function( global, factory ) {
-
- 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 ) {
-
-// Support: Firefox 18+
-// Can't be in strict mode, several libs including ASP.NET trace
-// the stack via arguments.caller.callee and Firefox dies if
-// you try to trace through "use strict" call chains. (#13335)
-//"use strict";
-var arr = [];
-
-var document = window.document;
-
-var slice = arr.slice;
-
-var concat = arr.concat;
-
-var push = arr.push;
-
-var indexOf = arr.indexOf;
-
-var class2type = {};
-
-var toString = class2type.toString;
-
-var hasOwn = class2type.hasOwnProperty;
-
-var support = {};
-
-
-
-var
- version = "2.2.4",
-
- // Define a local copy of jQuery
- jQuery = function( selector, context ) {
-
- // The jQuery object is actually just the init constructor 'enhanced'
- // Need init if jQuery is called (just allow error to be thrown if not included)
- return new jQuery.fn.init( selector, context );
- },
-
- // Support: Android<4.1
- // Make sure we trim BOM and NBSP
- rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
-
- // Matches dashed string for camelizing
- rmsPrefix = /^-ms-/,
- rdashAlpha = /-([\da-z])/gi,
-
- // Used by jQuery.camelCase as callback to replace()
- fcamelCase = function( all, letter ) {
- return letter.toUpperCase();
- };
-
-jQuery.fn = jQuery.prototype = {
-
- // The current version of jQuery being used
- jquery: version,
-
- constructor: jQuery,
-
- // Start with an empty selector
- selector: "",
-
- // The default length of a jQuery object is 0
- length: 0,
-
- toArray: function() {
- return slice.call( this );
- },
-
- // Get the Nth element in the matched element set OR
- // Get the whole matched element set as a clean array
- get: function( num ) {
- return num != null ?
-
- // Return just the one element from the set
- ( num < 0 ? this[ num + this.length ] : this[ num ] ) :
-
- // Return all the elements in a clean array
- slice.call( this );
- },
-
- // Take an array of elements and push it onto the stack
- // (returning the new matched element set)
- pushStack: function( elems ) {
-
- // Build a new jQuery matched element set
- var ret = jQuery.merge( this.constructor(), elems );
-
- // Add the old object onto the stack (as a reference)
- ret.prevObject = this;
- ret.context = this.context;
-
- // Return the newly-formed element set
- return ret;
- },
-
- // Execute a callback for every element in the matched set.
- each: function( callback ) {
- return jQuery.each( this, callback );
- },
-
- map: function( callback ) {
- return this.pushStack( jQuery.map( this, function( elem, i ) {
- return callback.call( elem, i, elem );
- } ) );
- },
-
- slice: function() {
- return this.pushStack( slice.apply( this, arguments ) );
- },
-
- first: function() {
- return this.eq( 0 );
- },
-
- last: function() {
- return this.eq( -1 );
- },
-
- eq: function( i ) {
- var len = this.length,
- j = +i + ( i < 0 ? len : 0 );
- return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] );
- },
-
- end: function() {
- return this.prevObject || this.constructor();
- },
-
- // For internal use only.
- // Behaves like an Array's method, not like a jQuery method.
- push: push,
- sort: arr.sort,
- splice: arr.splice
-};
-
-jQuery.extend = jQuery.fn.extend = function() {
- var options, name, src, copy, copyIsArray, clone,
- target = arguments[ 0 ] || {},
- i = 1,
- length = arguments.length,
- deep = false;
-
- // Handle a deep copy situation
- if ( typeof target === "boolean" ) {
- deep = target;
-
- // Skip the boolean and the target
- target = arguments[ i ] || {};
- i++;
- }
-
- // Handle case when target is a string or something (possible in deep copy)
- if ( typeof target !== "object" && !jQuery.isFunction( target ) ) {
- target = {};
- }
-
- // Extend jQuery itself if only one argument is passed
- if ( i === length ) {
- target = this;
- i--;
- }
-
- for ( ; i < length; i++ ) {
-
- // Only deal with non-null/undefined values
- if ( ( options = arguments[ i ] ) != null ) {
-
- // Extend the base object
- for ( name in options ) {
- src = target[ name ];
- copy = options[ name ];
-
- // Prevent never-ending loop
- if ( target === copy ) {
- continue;
- }
-
- // Recurse if we're merging plain objects or arrays
- if ( deep && copy && ( jQuery.isPlainObject( copy ) ||
- ( copyIsArray = jQuery.isArray( copy ) ) ) ) {
-
- if ( copyIsArray ) {
- copyIsArray = false;
- clone = src && jQuery.isArray( src ) ? src : [];
-
- } else {
- clone = src && jQuery.isPlainObject( src ) ? src : {};
- }
-
- // Never move original objects, clone them
- target[ name ] = jQuery.extend( deep, clone, copy );
-
- // Don't bring in undefined values
- } else if ( copy !== undefined ) {
- target[ name ] = copy;
- }
- }
- }
- }
-
- // Return the modified object
- return target;
-};
-
-jQuery.extend( {
-
- // Unique for each copy of jQuery on the page
- expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ),
-
- // Assume jQuery is ready without the ready module
- isReady: true,
-
- error: function( msg ) {
- throw new Error( msg );
- },
-
- noop: function() {},
-
- isFunction: function( obj ) {
- return jQuery.type( obj ) === "function";
- },
-
- isArray: Array.isArray,
-
- isWindow: function( obj ) {
- return obj != null && obj === obj.window;
- },
-
- isNumeric: function( obj ) {
-
- // parseFloat NaNs numeric-cast false positives (null|true|false|"")
- // ...but misinterprets leading-number strings, particularly hex literals ("0x...")
- // subtraction forces infinities to NaN
- // adding 1 corrects loss of precision from parseFloat (#15100)
- var realStringObj = obj && obj.toString();
- return !jQuery.isArray( obj ) && ( realStringObj - parseFloat( realStringObj ) + 1 ) >= 0;
- },
-
- isPlainObject: function( obj ) {
- var key;
-
- // Not plain objects:
- // - Any object or value whose internal [[Class]] property is not "[object Object]"
- // - DOM nodes
- // - window
- if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
- return false;
- }
-
- // Not own constructor property must be Object
- if ( obj.constructor &&
- !hasOwn.call( obj, "constructor" ) &&
- !hasOwn.call( obj.constructor.prototype || {}, "isPrototypeOf" ) ) {
- return false;
- }
-
- // Own properties are enumerated firstly, so to speed up,
- // if last one is own, then all properties are own
- for ( key in obj ) {}
-
- return key === undefined || hasOwn.call( obj, key );
- },
-
- isEmptyObject: function( obj ) {
- var name;
- for ( name in obj ) {
- return false;
- }
- return true;
- },
-
- type: function( obj ) {
- if ( obj == null ) {
- return obj + "";
- }
-
- // Support: Android<4.0, iOS<6 (functionish RegExp)
- return typeof obj === "object" || typeof obj === "function" ?
- class2type[ toString.call( obj ) ] || "object" :
- typeof obj;
- },
-
- // Evaluates a script in a global context
- globalEval: function( code ) {
- var script,
- indirect = eval;
-
- code = jQuery.trim( code );
-
- if ( code ) {
-
- // If the code includes a valid, prologue position
- // strict mode pragma, execute code by injecting a
- // script tag into the document.
- if ( code.indexOf( "use strict" ) === 1 ) {
- script = document.createElement( "script" );
- script.text = code;
- document.head.appendChild( script ).parentNode.removeChild( script );
- } else {
-
- // Otherwise, avoid the DOM node creation, insertion
- // and removal by using an indirect global eval
-
- indirect( code );
- }
- }
- },
-
- // Convert dashed to camelCase; used by the css and data modules
- // Support: IE9-11+
- // Microsoft forgot to hump their vendor prefix (#9572)
- camelCase: function( string ) {
- return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
- },
-
- nodeName: function( elem, name ) {
- return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
- },
-
- each: function( obj, callback ) {
- var length, i = 0;
-
- if ( isArrayLike( obj ) ) {
- length = obj.length;
- for ( ; i < length; i++ ) {
- if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
- break;
- }
- }
- } else {
- for ( i in obj ) {
- if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
- break;
- }
- }
- }
-
- return obj;
- },
-
- // Support: Android<4.1
- trim: function( text ) {
- return text == null ?
- "" :
- ( text + "" ).replace( rtrim, "" );
- },
-
- // results is for internal usage only
- makeArray: function( arr, results ) {
- var ret = results || [];
-
- if ( arr != null ) {
- if ( isArrayLike( Object( arr ) ) ) {
- jQuery.merge( ret,
- typeof arr === "string" ?
- [ arr ] : arr
- );
- } else {
- push.call( ret, arr );
- }
- }
-
- return ret;
- },
-
- inArray: function( elem, arr, i ) {
- return arr == null ? -1 : indexOf.call( arr, elem, i );
- },
-
- merge: function( first, second ) {
- var len = +second.length,
- j = 0,
- i = first.length;
-
- for ( ; j < len; j++ ) {
- first[ i++ ] = second[ j ];
- }
-
- first.length = i;
-
- return first;
- },
-
- grep: function( elems, callback, invert ) {
- var callbackInverse,
- matches = [],
- i = 0,
- length = elems.length,
- callbackExpect = !invert;
-
- // Go through the array, only saving the items
- // that pass the validator function
- for ( ; i < length; i++ ) {
- callbackInverse = !callback( elems[ i ], i );
- if ( callbackInverse !== callbackExpect ) {
- matches.push( elems[ i ] );
- }
- }
-
- return matches;
- },
-
- // arg is for internal usage only
- map: function( elems, callback, arg ) {
- var length, value,
- i = 0,
- ret = [];
-
- // Go through the array, translating each of the items to their new values
- if ( isArrayLike( elems ) ) {
- length = elems.length;
- for ( ; i < length; i++ ) {
- value = callback( elems[ i ], i, arg );
-
- if ( value != null ) {
- ret.push( value );
- }
- }
-
- // Go through every key on the object,
- } else {
- for ( i in elems ) {
- value = callback( elems[ i ], i, arg );
-
- if ( value != null ) {
- ret.push( value );
- }
- }
- }
-
- // Flatten any nested arrays
- return concat.apply( [], ret );
- },
-
- // A global GUID counter for objects
- guid: 1,
-
- // Bind a function to a context, optionally partially applying any
- // arguments.
- proxy: function( fn, context ) {
- var tmp, args, proxy;
-
- if ( typeof context === "string" ) {
- tmp = fn[ context ];
- context = fn;
- fn = tmp;
- }
-
- // Quick check to determine if target is callable, in the spec
- // this throws a TypeError, but we will just return undefined.
- if ( !jQuery.isFunction( fn ) ) {
- return undefined;
- }
-
- // Simulated bind
- args = slice.call( arguments, 2 );
- proxy = function() {
- return fn.apply( context || this, args.concat( slice.call( arguments ) ) );
- };
-
- // Set the guid of unique handler to the same of original handler, so it can be removed
- proxy.guid = fn.guid = fn.guid || jQuery.guid++;
-
- return proxy;
- },
-
- now: Date.now,
-
- // jQuery.support is not used in Core but other projects attach their
- // properties to it so it needs to exist.
- support: support
-} );
-
-// JSHint would error on this code due to the Symbol not being defined in ES5.
-// Defining this global in .jshintrc would create a danger of using the global
-// unguarded in another place, it seems safer to just disable JSHint for these
-// three lines.
-/* jshint ignore: start */
-if ( typeof Symbol === "function" ) {
- jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ];
-}
-/* jshint ignore: end */
-
-// 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: iOS 8.2 (not reproducible in simulator)
- // `in` check used to prevent JIT error (gh-2145)
- // hasOwn isn't used here due to false negatives
- // regarding Nodelist length in IE
- var length = !!obj && "length" in obj && obj.length,
- type = jQuery.type( obj );
-
- if ( type === "function" || jQuery.isWindow( obj ) ) {
- return false;
- }
-
- return type === "array" || length === 0 ||
- typeof length === "number" && length > 0 && ( length - 1 ) in obj;
-}
-var Sizzle =
-/*!
- * Sizzle CSS Selector Engine v2.2.1
- * http://sizzlejs.com/
- *
- * Copyright jQuery Foundation and other contributors
- * Released under the MIT license
- * http://jquery.org/license
- *
- * Date: 2015-10-17
- */
-(function( window ) {
-
-var i,
- support,
- Expr,
- getText,
- isXML,
- tokenize,
- compile,
- select,
- outermostContext,
- sortInput,
- hasDuplicate,
-
- // Local document vars
- setDocument,
- document,
- docElem,
- documentIsHTML,
- rbuggyQSA,
- rbuggyMatches,
- matches,
- contains,
-
- // Instance-specific data
- expando = "sizzle" + 1 * new Date(),
- preferredDoc = window.document,
- dirruns = 0,
- done = 0,
- classCache = createCache(),
- tokenCache = createCache(),
- compilerCache = createCache(),
- sortOrder = function( a, b ) {
- if ( a === b ) {
- hasDuplicate = true;
- }
- return 0;
- },
-
- // General-purpose constants
- MAX_NEGATIVE = 1 << 31,
-
- // Instance methods
- hasOwn = ({}).hasOwnProperty,
- arr = [],
- pop = arr.pop,
- push_native = arr.push,
- push = arr.push,
- slice = arr.slice,
- // Use a stripped-down indexOf as it's faster than native
- // http://jsperf.com/thor-indexof-vs-for/5
- indexOf = function( list, elem ) {
- var i = 0,
- len = list.length;
- for ( ; i < len; i++ ) {
- if ( list[i] === elem ) {
- return i;
- }
- }
- return -1;
- },
-
- booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",
-
- // Regular expressions
-
- // http://www.w3.org/TR/css3-selectors/#whitespace
- whitespace = "[\\x20\\t\\r\\n\\f]",
-
- // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
- identifier = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
-
- // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
- attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace +
- // Operator (capture 2)
- "*([*^$|!~]?=)" + whitespace +
- // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"
- "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace +
- "*\\]",
-
- pseudos = ":(" + identifier + ")(?:\\((" +
- // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments:
- // 1. quoted (capture 3; capture 4 or capture 5)
- "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" +
- // 2. simple (capture 6)
- "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" +
- // 3. anything else (capture 2)
- ".*" +
- ")\\)|)",
-
- // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
- rwhitespace = new RegExp( whitespace + "+", "g" ),
- rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
-
- rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
- rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),
-
- rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ),
-
- rpseudo = new RegExp( pseudos ),
- ridentifier = new RegExp( "^" + identifier + "$" ),
-
- matchExpr = {
- "ID": new RegExp( "^#(" + identifier + ")" ),
- "CLASS": new RegExp( "^\\.(" + identifier + ")" ),
- "TAG": new RegExp( "^(" + identifier + "|[*])" ),
- "ATTR": new RegExp( "^" + attributes ),
- "PSEUDO": new RegExp( "^" + pseudos ),
- "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
- "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
- "*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
- "bool": new RegExp( "^(?:" + booleans + ")$", "i" ),
- // For use in libraries implementing .is()
- // We use this for POS matching in `select`
- "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
- whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
- },
-
- rinputs = /^(?:input|select|textarea|button)$/i,
- rheader = /^h\d$/i,
-
- rnative = /^[^{]+\{\s*\[native \w/,
-
- // Easily-parseable/retrievable ID or TAG or CLASS selectors
- rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
-
- rsibling = /[+~]/,
- rescape = /'|\\/g,
-
- // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
- runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
- funescape = function( _, escaped, escapedWhitespace ) {
- var high = "0x" + escaped - 0x10000;
- // NaN means non-codepoint
- // Support: Firefox<24
- // Workaround erroneous numeric interpretation of +"0x"
- return high !== high || escapedWhitespace ?
- escaped :
- high < 0 ?
- // BMP codepoint
- String.fromCharCode( high + 0x10000 ) :
- // Supplemental Plane codepoint (surrogate pair)
- String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
- },
-
- // Used for iframes
- // See setDocument()
- // Removing the function wrapper causes a "Permission Denied"
- // error in IE
- unloadHandler = function() {
- setDocument();
- };
-
-// Optimize for push.apply( _, NodeList )
-try {
- push.apply(
- (arr = slice.call( preferredDoc.childNodes )),
- preferredDoc.childNodes
- );
- // Support: Android<4.0
- // Detect silently failing push.apply
- arr[ preferredDoc.childNodes.length ].nodeType;
-} catch ( e ) {
- push = { apply: arr.length ?
-
- // Leverage slice if possible
- function( target, els ) {
- push_native.apply( target, slice.call(els) );
- } :
-
- // Support: IE<9
- // Otherwise append directly
- function( target, els ) {
- var j = target.length,
- i = 0;
- // Can't trust NodeList.length
- while ( (target[j++] = els[i++]) ) {}
- target.length = j - 1;
- }
- };
-}
-
-function Sizzle( selector, context, results, seed ) {
- var m, i, elem, nid, nidselect, match, groups, newSelector,
- newContext = context && context.ownerDocument,
-
- // nodeType defaults to 9, since context defaults to document
- nodeType = context ? context.nodeType : 9;
-
- results = results || [];
-
- // Return early from calls with invalid selector or context
- if ( typeof selector !== "string" || !selector ||
- nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) {
-
- return results;
- }
-
- // Try to shortcut find operations (as opposed to filters) in HTML documents
- if ( !seed ) {
-
- if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
- setDocument( context );
- }
- context = context || document;
-
- if ( documentIsHTML ) {
-
- // If the selector is sufficiently simple, try using a "get*By*" DOM method
- // (excepting DocumentFragment context, where the methods don't exist)
- if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) {
-
- // ID selector
- if ( (m = match[1]) ) {
-
- // Document context
- if ( nodeType === 9 ) {
- if ( (elem = context.getElementById( m )) ) {
-
- // Support: IE, Opera, Webkit
- // TODO: identify versions
- // getElementById can match elements by name instead of ID
- if ( elem.id === m ) {
- results.push( elem );
- return results;
- }
- } else {
- return results;
- }
-
- // Element context
- } else {
-
- // Support: IE, Opera, Webkit
- // TODO: identify versions
- // getElementById can match elements by name instead of ID
- if ( newContext && (elem = newContext.getElementById( m )) &&
- contains( context, elem ) &&
- elem.id === m ) {
-
- results.push( elem );
- return results;
- }
- }
-
- // Type selector
- } else if ( match[2] ) {
- push.apply( results, context.getElementsByTagName( selector ) );
- return results;
-
- // Class selector
- } else if ( (m = match[3]) && support.getElementsByClassName &&
- context.getElementsByClassName ) {
-
- push.apply( results, context.getElementsByClassName( m ) );
- return results;
- }
- }
-
- // Take advantage of querySelectorAll
- if ( support.qsa &&
- !compilerCache[ selector + " " ] &&
- (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
-
- if ( nodeType !== 1 ) {
- newContext = context;
- newSelector = selector;
-
- // qSA looks outside Element context, which is not what we want
- // Thanks to Andrew Dupont for this workaround technique
- // Support: IE <=8
- // Exclude object elements
- } else if ( context.nodeName.toLowerCase() !== "object" ) {
-
- // Capture the context ID, setting it first if necessary
- if ( (nid = context.getAttribute( "id" )) ) {
- nid = nid.replace( rescape, "\\$&" );
- } else {
- context.setAttribute( "id", (nid = expando) );
- }
-
- // Prefix every selector in the list
- groups = tokenize( selector );
- i = groups.length;
- nidselect = ridentifier.test( nid ) ? "#" + nid : "[id='" + nid + "']";
- while ( i-- ) {
- groups[i] = nidselect + " " + toSelector( groups[i] );
- }
- newSelector = groups.join( "," );
-
- // Expand context for sibling selectors
- newContext = rsibling.test( selector ) && testContext( context.parentNode ) ||
- context;
- }
-
- if ( newSelector ) {
- try {
- push.apply( results,
- newContext.querySelectorAll( newSelector )
- );
- return results;
- } catch ( qsaError ) {
- } finally {
- if ( nid === expando ) {
- context.removeAttribute( "id" );
- }
- }
- }
- }
- }
- }
-
- // All others
- return select( selector.replace( rtrim, "$1" ), context, results, seed );
-}
-
-/**
- * Create key-value caches of limited size
- * @returns {function(string, object)} Returns the Object data after storing it on itself with
- * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
- * deleting the oldest entry
- */
-function createCache() {
- var keys = [];
-
- function cache( key, value ) {
- // Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
- if ( keys.push( key + " " ) > Expr.cacheLength ) {
- // Only keep the most recent entries
- delete cache[ keys.shift() ];
- }
- return (cache[ key + " " ] = value);
- }
- return cache;
-}
-
-/**
- * Mark a function for special use by Sizzle
- * @param {Function} fn The function to mark
- */
-function markFunction( fn ) {
- fn[ expando ] = true;
- return fn;
-}
-
-/**
- * Support testing using an element
- * @param {Function} fn Passed the created div and expects a boolean result
- */
-function assert( fn ) {
- var div = document.createElement("div");
-
- try {
- return !!fn( div );
- } catch (e) {
- return false;
- } finally {
- // Remove from its parent by default
- if ( div.parentNode ) {
- div.parentNode.removeChild( div );
- }
- // release memory in IE
- div = 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 &&
- ( ~b.sourceIndex || MAX_NEGATIVE ) -
- ( ~a.sourceIndex || MAX_NEGATIVE );
-
- // 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 positionals
- * @param {Function} fn
- */
-function createPositionalPseudo( fn ) {
- return markFunction(function( argument ) {
- argument = +argument;
- return markFunction(function( seed, matches ) {
- var j,
- matchIndexes = fn( [], seed.length, argument ),
- i = matchIndexes.length;
-
- // Match elements found at the specified indexes
- while ( i-- ) {
- if ( seed[ (j = matchIndexes[i]) ] ) {
- seed[j] = !(matches[j] = seed[j]);
- }
- }
- });
- });
-}
-
-/**
- * Checks a node for validity as a Sizzle context
- * @param {Element|Object=} context
- * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
- */
-function testContext( context ) {
- return context && typeof context.getElementsByTagName !== "undefined" && context;
-}
-
-// Expose support vars for convenience
-support = Sizzle.support = {};
-
-/**
- * Detects XML nodes
- * @param {Element|Object} elem An element or a document
- * @returns {Boolean} True iff elem is a non-HTML XML node
- */
-isXML = Sizzle.isXML = function( elem ) {
- // documentElement is verified for cases where it doesn't yet exist
- // (such as loading iframes in IE - #4833)
- var documentElement = elem && (elem.ownerDocument || elem).documentElement;
- return documentElement ? documentElement.nodeName !== "HTML" : false;
-};
-
-/**
- * Sets document-related variables once based on the current document
- * @param {Element|Object} [doc] An element or document object to use to set the document
- * @returns {Object} Returns the current document
- */
-setDocument = Sizzle.setDocument = function( node ) {
- var hasCompare, parent,
- doc = node ? node.ownerDocument || node : preferredDoc;
-
- // Return early if doc is invalid or already selected
- if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
- return document;
- }
-
- // Update global variables
- document = doc;
- docElem = document.documentElement;
- documentIsHTML = !isXML( document );
-
- // Support: IE 9-11, Edge
- // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936)
- if ( (parent = document.defaultView) && parent.top !== parent ) {
- // Support: IE 11
- if ( parent.addEventListener ) {
- parent.addEventListener( "unload", unloadHandler, false );
-
- // Support: IE 9 - 10 only
- } else if ( parent.attachEvent ) {
- parent.attachEvent( "onunload", unloadHandler );
- }
- }
-
- /* Attributes
- ---------------------------------------------------------------------- */
-
- // Support: IE<8
- // Verify that getAttribute really returns attributes and not properties
- // (excepting IE8 booleans)
- support.attributes = assert(function( div ) {
- div.className = "i";
- return !div.getAttribute("className");
- });
-
- /* getElement(s)By*
- ---------------------------------------------------------------------- */
-
- // Check if getElementsByTagName("*") returns only elements
- support.getElementsByTagName = assert(function( div ) {
- div.appendChild( document.createComment("") );
- return !div.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 programatically-set names,
- // so use a roundabout getElementsByName test
- support.getById = assert(function( div ) {
- docElem.appendChild( div ).id = expando;
- return !document.getElementsByName || !document.getElementsByName( expando ).length;
- });
-
- // ID find and filter
- if ( support.getById ) {
- Expr.find["ID"] = function( id, context ) {
- if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {
- var m = context.getElementById( id );
- return m ? [ m ] : [];
- }
- };
- Expr.filter["ID"] = function( id ) {
- var attrId = id.replace( runescape, funescape );
- return function( elem ) {
- return elem.getAttribute("id") === attrId;
- };
- };
- } else {
- // Support: IE6/7
- // getElementById is not reliable as a find shortcut
- delete Expr.find["ID"];
-
- Expr.filter["ID"] = function( id ) {
- var attrId = id.replace( runescape, funescape );
- return function( elem ) {
- var node = typeof elem.getAttributeNode !== "undefined" &&
- elem.getAttributeNode("id");
- return node && node.value === attrId;
- };
- };
- }
-
- // Tag
- Expr.find["TAG"] = support.getElementsByTagName ?
- function( tag, context ) {
- if ( typeof context.getElementsByTagName !== "undefined" ) {
- return context.getElementsByTagName( tag );
-
- // DocumentFragment nodes don't have gEBTN
- } else if ( support.qsa ) {
- return context.querySelectorAll( tag );
- }
- } :
-
- function( tag, context ) {
- var elem,
- tmp = [],
- i = 0,
- // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too
- results = context.getElementsByTagName( tag );
-
- // Filter out possible comments
- if ( tag === "*" ) {
- while ( (elem = results[i++]) ) {
- if ( elem.nodeType === 1 ) {
- tmp.push( elem );
- }
- }
-
- return tmp;
- }
- return results;
- };
-
- // Class
- Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
- if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) {
- return context.getElementsByClassName( className );
- }
- };
-
- /* QSA/matchesSelector
- ---------------------------------------------------------------------- */
-
- // QSA and matchesSelector support
-
- // matchesSelector(:active) reports false when true (IE9/Opera 11.5)
- rbuggyMatches = [];
-
- // qSa(:focus) reports false when true (Chrome 21)
- // We allow this because of a bug in IE8/9 that throws an error
- // whenever `document.activeElement` is accessed on an iframe
- // So, we allow :focus to pass through QSA all the time to avoid the IE error
- // See http://bugs.jquery.com/ticket/13378
- rbuggyQSA = [];
-
- if ( (support.qsa = rnative.test( document.querySelectorAll )) ) {
- // Build QSA regex
- // Regex strategy adopted from Diego Perini
- assert(function( div ) {
- // 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
- // http://bugs.jquery.com/ticket/12359
- docElem.appendChild( div ).innerHTML = "" +
- "";
-
- // 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
- // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section
- if ( div.querySelectorAll("[msallowcapture^='']").length ) {
- rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
- }
-
- // Support: IE8
- // Boolean attributes and "value" are not treated correctly
- if ( !div.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 ( !div.querySelectorAll( "[id~=" + expando + "-]" ).length ) {
- rbuggyQSA.push("~=");
- }
-
- // Webkit/Opera - :checked should return selected option elements
- // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
- // IE8 throws error here and will not see later tests
- if ( !div.querySelectorAll(":checked").length ) {
- rbuggyQSA.push(":checked");
- }
-
- // Support: Safari 8+, iOS 8+
- // https://bugs.webkit.org/show_bug.cgi?id=136851
- // In-page `selector#id sibing-combinator selector` fails
- if ( !div.querySelectorAll( "a#" + expando + "+*" ).length ) {
- rbuggyQSA.push(".#.+[+~]");
- }
- });
-
- assert(function( div ) {
- // Support: Windows 8 Native Apps
- // The type and name attributes are restricted during .innerHTML assignment
- var input = document.createElement("input");
- input.setAttribute( "type", "hidden" );
- div.appendChild( input ).setAttribute( "name", "D" );
-
- // Support: IE8
- // Enforce case-sensitivity of name attribute
- if ( div.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 ( !div.querySelectorAll(":enabled").length ) {
- rbuggyQSA.push( ":enabled", ":disabled" );
- }
-
- // Opera 10-11 does not throw on post-comma invalid pseudos
- div.querySelectorAll("*,:x");
- rbuggyQSA.push(",.*:");
- });
- }
-
- if ( (support.matchesSelector = rnative.test( (matches = docElem.matches ||
- docElem.webkitMatchesSelector ||
- docElem.mozMatchesSelector ||
- docElem.oMatchesSelector ||
- docElem.msMatchesSelector) )) ) {
-
- assert(function( div ) {
- // Check to see if it's possible to do matchesSelector
- // on a disconnected node (IE 9)
- support.disconnectedMatch = matches.call( div, "div" );
-
- // This should fail with an exception
- // Gecko does not error, returns false instead
- matches.call( div, "[s!='']:x" );
- rbuggyMatches.push( "!=", pseudos );
- });
- }
-
- rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
- rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );
-
- /* Contains
- ---------------------------------------------------------------------- */
- hasCompare = rnative.test( docElem.compareDocumentPosition );
-
- // Element contains another
- // Purposefully self-exclusive
- // As in, an element does not contain itself
- contains = hasCompare || rnative.test( docElem.contains ) ?
- function( a, b ) {
- var adown = a.nodeType === 9 ? a.documentElement : a,
- bup = b && b.parentNode;
- return a === bup || !!( bup && bup.nodeType === 1 && (
- adown.contains ?
- adown.contains( bup ) :
- a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
- ));
- } :
- function( a, b ) {
- if ( b ) {
- while ( (b = b.parentNode) ) {
- if ( b === a ) {
- return true;
- }
- }
- }
- return false;
- };
-
- /* Sorting
- ---------------------------------------------------------------------- */
-
- // Document order sorting
- sortOrder = hasCompare ?
- function( a, b ) {
-
- // Flag for duplicate removal
- if ( a === b ) {
- hasDuplicate = true;
- return 0;
- }
-
- // Sort on method existence if only one input has compareDocumentPosition
- var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
- if ( compare ) {
- return compare;
- }
-
- // Calculate position if both inputs belong to the same document
- compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ?
- a.compareDocumentPosition( b ) :
-
- // Otherwise we know they are disconnected
- 1;
-
- // Disconnected nodes
- if ( compare & 1 ||
- (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {
-
- // Choose the first element that is related to our preferred document
- if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) {
- return -1;
- }
- if ( b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) {
- return 1;
- }
-
- // Maintain original order
- return sortInput ?
- ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
- 0;
- }
-
- return compare & 4 ? -1 : 1;
- } :
- function( a, b ) {
- // Exit early if the nodes are identical
- if ( a === b ) {
- hasDuplicate = true;
- return 0;
- }
-
- var cur,
- i = 0,
- aup = a.parentNode,
- bup = b.parentNode,
- ap = [ a ],
- bp = [ b ];
-
- // Parentless nodes are either documents or disconnected
- if ( !aup || !bup ) {
- return a === document ? -1 :
- b === document ? 1 :
- aup ? -1 :
- bup ? 1 :
- sortInput ?
- ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
- 0;
-
- // If the nodes are siblings, we can do a quick check
- } else if ( aup === bup ) {
- return siblingCheck( a, b );
- }
-
- // Otherwise we need full lists of their ancestors for comparison
- cur = a;
- while ( (cur = cur.parentNode) ) {
- ap.unshift( cur );
- }
- cur = b;
- while ( (cur = cur.parentNode) ) {
- bp.unshift( cur );
- }
-
- // Walk down the tree looking for a discrepancy
- while ( ap[i] === bp[i] ) {
- i++;
- }
-
- return i ?
- // Do a sibling check if the nodes have a common ancestor
- siblingCheck( ap[i], bp[i] ) :
-
- // Otherwise nodes in our document sort first
- ap[i] === preferredDoc ? -1 :
- bp[i] === preferredDoc ? 1 :
- 0;
- };
-
- return document;
-};
-
-Sizzle.matches = function( expr, elements ) {
- return Sizzle( expr, null, null, elements );
-};
-
-Sizzle.matchesSelector = function( elem, expr ) {
- // Set document vars if needed
- if ( ( elem.ownerDocument || elem ) !== document ) {
- setDocument( elem );
- }
-
- // Make sure that attribute selectors are quoted
- expr = expr.replace( rattributeQuotes, "='$1']" );
-
- if ( support.matchesSelector && documentIsHTML &&
- !compilerCache[ expr + " " ] &&
- ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
- ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) {
-
- try {
- var ret = matches.call( elem, expr );
-
- // IE 9's matchesSelector returns false on disconnected nodes
- if ( ret || support.disconnectedMatch ||
- // As well, disconnected nodes are said to be in a document
- // fragment in IE 9
- elem.document && elem.document.nodeType !== 11 ) {
- return ret;
- }
- } catch (e) {}
- }
-
- return Sizzle( expr, document, null, [ elem ] ).length > 0;
-};
-
-Sizzle.contains = function( context, elem ) {
- // Set document vars if needed
- if ( ( context.ownerDocument || context ) !== document ) {
- setDocument( context );
- }
- return contains( context, elem );
-};
-
-Sizzle.attr = function( elem, name ) {
- // Set document vars if needed
- if ( ( elem.ownerDocument || elem ) !== document ) {
- setDocument( elem );
- }
-
- var fn = Expr.attrHandle[ name.toLowerCase() ],
- // Don't get fooled by Object.prototype properties (jQuery #13807)
- val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
- fn( elem, name, !documentIsHTML ) :
- undefined;
-
- return val !== undefined ?
- val :
- support.attributes || !documentIsHTML ?
- elem.getAttribute( name ) :
- (val = elem.getAttributeNode(name)) && val.specified ?
- val.value :
- null;
-};
-
-Sizzle.error = function( msg ) {
- throw new Error( "Syntax error, unrecognized expression: " + msg );
-};
-
-/**
- * Document sorting and removing duplicates
- * @param {ArrayLike} results
- */
-Sizzle.uniqueSort = function( results ) {
- var elem,
- duplicates = [],
- j = 0,
- i = 0;
-
- // Unless we *know* we can detect duplicates, assume their presence
- hasDuplicate = !support.detectDuplicates;
- sortInput = !support.sortStable && results.slice( 0 );
- results.sort( sortOrder );
-
- if ( hasDuplicate ) {
- while ( (elem = results[i++]) ) {
- if ( elem === results[ i ] ) {
- j = duplicates.push( i );
- }
- }
- while ( j-- ) {
- results.splice( duplicates[ j ], 1 );
- }
- }
-
- // Clear input after sorting to release objects
- // See https://github.com/jquery/sizzle/pull/225
- sortInput = null;
-
- return results;
-};
-
-/**
- * Utility function for retrieving the text value of an array of DOM nodes
- * @param {Array|Element} elem
- */
-getText = Sizzle.getText = function( elem ) {
- var node,
- ret = "",
- i = 0,
- nodeType = elem.nodeType;
-
- if ( !nodeType ) {
- // If no nodeType, this is expected to be an array
- while ( (node = elem[i++]) ) {
- // Do not traverse comment nodes
- ret += getText( node );
- }
- } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
- // Use textContent for elements
- // innerText usage removed for consistency of new lines (jQuery #11153)
- if ( typeof elem.textContent === "string" ) {
- return elem.textContent;
- } else {
- // Traverse its children
- for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
- ret += getText( elem );
- }
- }
- } else if ( nodeType === 3 || nodeType === 4 ) {
- return elem.nodeValue;
- }
- // Do not include comment or processing instruction nodes
-
- return ret;
-};
-
-Expr = Sizzle.selectors = {
-
- // Can be adjusted by the user
- cacheLength: 50,
-
- createPseudo: markFunction,
-
- match: matchExpr,
-
- attrHandle: {},
-
- find: {},
-
- relative: {
- ">": { dir: "parentNode", first: true },
- " ": { dir: "parentNode" },
- "+": { dir: "previousSibling", first: true },
- "~": { dir: "previousSibling" }
- },
-
- preFilter: {
- "ATTR": function( match ) {
- match[1] = match[1].replace( runescape, funescape );
-
- // Move the given value to match[3] whether quoted or unquoted
- match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape );
-
- if ( match[2] === "~=" ) {
- match[3] = " " + match[3] + " ";
- }
-
- return match.slice( 0, 4 );
- },
-
- "CHILD": function( match ) {
- /* matches from matchExpr["CHILD"]
- 1 type (only|nth|...)
- 2 what (child|of-type)
- 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
- 4 xn-component of xn+y argument ([+-]?\d*n|)
- 5 sign of xn-component
- 6 x of xn-component
- 7 sign of y-component
- 8 y of y-component
- */
- match[1] = match[1].toLowerCase();
-
- if ( match[1].slice( 0, 3 ) === "nth" ) {
- // nth-* requires argument
- if ( !match[3] ) {
- Sizzle.error( match[0] );
- }
-
- // numeric x and y parameters for Expr.filter.CHILD
- // remember that false/true cast respectively to 0/1
- match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
- match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
-
- // other types prohibit arguments
- } else if ( match[3] ) {
- Sizzle.error( match[0] );
- }
-
- return match;
- },
-
- "PSEUDO": function( match ) {
- var excess,
- unquoted = !match[6] && match[2];
-
- if ( matchExpr["CHILD"].test( match[0] ) ) {
- return null;
- }
-
- // Accept quoted arguments as-is
- if ( match[3] ) {
- match[2] = match[4] || match[5] || "";
-
- // Strip excess characters from unquoted arguments
- } else if ( unquoted && rpseudo.test( unquoted ) &&
- // Get excess from tokenize (recursively)
- (excess = tokenize( unquoted, true )) &&
- // advance to the next closing parenthesis
- (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
-
- // excess is a negative index
- match[0] = match[0].slice( 0, excess );
- match[2] = unquoted.slice( 0, excess );
- }
-
- // Return only captures needed by the pseudo filter method (type and argument)
- return match.slice( 0, 3 );
- }
- },
-
- filter: {
-
- "TAG": function( nodeNameSelector ) {
- var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
- return nodeNameSelector === "*" ?
- function() { return true; } :
- function( elem ) {
- return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
- };
- },
-
- "CLASS": function( className ) {
- var pattern = classCache[ className + " " ];
-
- return pattern ||
- (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
- classCache( className, function( elem ) {
- return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" );
- });
- },
-
- "ATTR": function( name, operator, check ) {
- return function( elem ) {
- var result = Sizzle.attr( elem, name );
-
- if ( result == null ) {
- return operator === "!=";
- }
- if ( !operator ) {
- return true;
- }
-
- result += "";
-
- return operator === "=" ? result === check :
- operator === "!=" ? result !== check :
- operator === "^=" ? check && result.indexOf( check ) === 0 :
- operator === "*=" ? check && result.indexOf( check ) > -1 :
- operator === "$=" ? check && result.slice( -check.length ) === check :
- operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 :
- operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
- false;
- };
- },
-
- "CHILD": function( type, what, argument, first, last ) {
- var simple = type.slice( 0, 3 ) !== "nth",
- forward = type.slice( -4 ) !== "last",
- ofType = what === "of-type";
-
- return first === 1 && last === 0 ?
-
- // Shortcut for :nth-*(n)
- function( elem ) {
- return !!elem.parentNode;
- } :
-
- function( elem, context, xml ) {
- var cache, uniqueCache, outerCache, node, nodeIndex, start,
- dir = simple !== forward ? "nextSibling" : "previousSibling",
- parent = elem.parentNode,
- name = ofType && elem.nodeName.toLowerCase(),
- useCache = !xml && !ofType,
- diff = false;
-
- if ( parent ) {
-
- // :(first|last|only)-(child|of-type)
- if ( simple ) {
- while ( dir ) {
- node = elem;
- while ( (node = node[ dir ]) ) {
- if ( ofType ?
- node.nodeName.toLowerCase() === name :
- node.nodeType === 1 ) {
-
- return false;
- }
- }
- // Reverse direction for :only-* (if we haven't yet done so)
- start = dir = type === "only" && !start && "nextSibling";
- }
- return true;
- }
-
- start = [ forward ? parent.firstChild : parent.lastChild ];
-
- // non-xml :nth-child(...) stores cache data on `parent`
- if ( forward && useCache ) {
-
- // Seek `elem` from a previously-cached index
-
- // ...in a gzip-friendly way
- node = parent;
- outerCache = node[ expando ] || (node[ expando ] = {});
-
- // Support: IE <9 only
- // Defend against cloned attroperties (jQuery gh-1709)
- uniqueCache = outerCache[ node.uniqueID ] ||
- (outerCache[ node.uniqueID ] = {});
-
- cache = uniqueCache[ type ] || [];
- nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
- diff = nodeIndex && cache[ 2 ];
- node = nodeIndex && parent.childNodes[ nodeIndex ];
-
- while ( (node = ++nodeIndex && node && node[ dir ] ||
-
- // Fallback to seeking `elem` from the start
- (diff = nodeIndex = 0) || start.pop()) ) {
-
- // When found, cache indexes on `parent` and break
- if ( node.nodeType === 1 && ++diff && node === elem ) {
- uniqueCache[ type ] = [ dirruns, nodeIndex, diff ];
- break;
- }
- }
-
- } else {
- // Use previously-cached element index if available
- if ( useCache ) {
- // ...in a gzip-friendly way
- node = elem;
- outerCache = node[ expando ] || (node[ expando ] = {});
-
- // Support: IE <9 only
- // Defend against cloned attroperties (jQuery gh-1709)
- uniqueCache = outerCache[ node.uniqueID ] ||
- (outerCache[ node.uniqueID ] = {});
-
- cache = uniqueCache[ type ] || [];
- nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
- diff = nodeIndex;
- }
-
- // xml :nth-child(...)
- // or :nth-last-child(...) or :nth(-last)?-of-type(...)
- if ( diff === false ) {
- // Use the same loop as above to seek `elem` from the start
- while ( (node = ++nodeIndex && node && node[ dir ] ||
- (diff = nodeIndex = 0) || start.pop()) ) {
-
- if ( ( ofType ?
- node.nodeName.toLowerCase() === name :
- node.nodeType === 1 ) &&
- ++diff ) {
-
- // Cache the index of each encountered element
- if ( useCache ) {
- outerCache = node[ expando ] || (node[ expando ] = {});
-
- // Support: IE <9 only
- // Defend against cloned attroperties (jQuery gh-1709)
- uniqueCache = outerCache[ node.uniqueID ] ||
- (outerCache[ node.uniqueID ] = {});
-
- uniqueCache[ type ] = [ dirruns, diff ];
- }
-
- if ( node === elem ) {
- break;
- }
- }
- }
- }
- }
-
- // Incorporate the offset, then check against cycle size
- diff -= last;
- return diff === first || ( diff % first === 0 && diff / first >= 0 );
- }
- };
- },
-
- "PSEUDO": function( pseudo, argument ) {
- // pseudo-class names are case-insensitive
- // http://www.w3.org/TR/selectors/#pseudo-classes
- // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
- // Remember that setFilters inherits from pseudos
- var args,
- fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
- Sizzle.error( "unsupported pseudo: " + pseudo );
-
- // The user may use createPseudo to indicate that
- // arguments are needed to create the filter function
- // just as Sizzle does
- if ( fn[ expando ] ) {
- return fn( argument );
- }
-
- // But maintain support for old signatures
- if ( fn.length > 1 ) {
- args = [ pseudo, pseudo, "", argument ];
- return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
- markFunction(function( seed, matches ) {
- var idx,
- matched = fn( seed, argument ),
- i = matched.length;
- while ( i-- ) {
- idx = indexOf( seed, matched[i] );
- seed[ idx ] = !( matches[ idx ] = matched[i] );
- }
- }) :
- function( elem ) {
- return fn( elem, 0, args );
- };
- }
-
- return fn;
- }
- },
-
- pseudos: {
- // Potentially complex pseudos
- "not": markFunction(function( selector ) {
- // Trim the selector passed to compile
- // to avoid treating leading and trailing
- // spaces as combinators
- var input = [],
- results = [],
- matcher = compile( selector.replace( rtrim, "$1" ) );
-
- return matcher[ expando ] ?
- markFunction(function( seed, matches, context, xml ) {
- var elem,
- unmatched = matcher( seed, null, xml, [] ),
- i = seed.length;
-
- // Match elements unmatched by `matcher`
- while ( i-- ) {
- if ( (elem = unmatched[i]) ) {
- seed[i] = !(matches[i] = elem);
- }
- }
- }) :
- function( elem, context, xml ) {
- input[0] = elem;
- matcher( input, null, xml, results );
- // Don't keep the element (issue #299)
- input[0] = null;
- return !results.pop();
- };
- }),
-
- "has": markFunction(function( selector ) {
- return function( elem ) {
- return Sizzle( selector, elem ).length > 0;
- };
- }),
-
- "contains": markFunction(function( text ) {
- text = text.replace( runescape, funescape );
- return function( elem ) {
- return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
- };
- }),
-
- // "Whether an element is represented by a :lang() selector
- // is based solely on the element's language value
- // being equal to the identifier C,
- // or beginning with the identifier C immediately followed by "-".
- // The matching of C against the element's language value is performed case-insensitively.
- // The identifier C does not have to be a valid language name."
- // http://www.w3.org/TR/selectors/#lang-pseudo
- "lang": markFunction( function( lang ) {
- // lang value must be a valid identifier
- if ( !ridentifier.test(lang || "") ) {
- Sizzle.error( "unsupported lang: " + lang );
- }
- lang = lang.replace( runescape, funescape ).toLowerCase();
- return function( elem ) {
- var elemLang;
- do {
- if ( (elemLang = documentIsHTML ?
- elem.lang :
- elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {
-
- elemLang = elemLang.toLowerCase();
- return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
- }
- } while ( (elem = elem.parentNode) && elem.nodeType === 1 );
- return false;
- };
- }),
-
- // Miscellaneous
- "target": function( elem ) {
- var hash = window.location && window.location.hash;
- return hash && hash.slice( 1 ) === elem.id;
- },
-
- "root": function( elem ) {
- return elem === docElem;
- },
-
- "focus": function( elem ) {
- return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
- },
-
- // Boolean properties
- "enabled": function( elem ) {
- return elem.disabled === false;
- },
-
- "disabled": function( elem ) {
- return elem.disabled === true;
- },
-
- "checked": function( elem ) {
- // In CSS3, :checked should return both checked and selected elements
- // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
- var nodeName = elem.nodeName.toLowerCase();
- return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
- },
-
- "selected": function( elem ) {
- // Accessing this property makes selected-by-default
- // options in Safari work properly
- if ( elem.parentNode ) {
- elem.parentNode.selectedIndex;
- }
-
- return elem.selected === true;
- },
-
- // Contents
- "empty": function( elem ) {
- // http://www.w3.org/TR/selectors/#empty-pseudo
- // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
- // but not by others (comment: 8; processing instruction: 7; etc.)
- // nodeType < 6 works because attributes (2) do not appear as children
- for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
- if ( elem.nodeType < 6 ) {
- return false;
- }
- }
- return true;
- },
-
- "parent": function( elem ) {
- return !Expr.pseudos["empty"]( elem );
- },
-
- // Element/input types
- "header": function( elem ) {
- return rheader.test( elem.nodeName );
- },
-
- "input": function( elem ) {
- return rinputs.test( elem.nodeName );
- },
-
- "button": function( elem ) {
- var name = elem.nodeName.toLowerCase();
- return name === "input" && elem.type === "button" || name === "button";
- },
-
- "text": function( elem ) {
- var attr;
- return elem.nodeName.toLowerCase() === "input" &&
- elem.type === "text" &&
-
- // Support: IE<8
- // New HTML5 attribute values (e.g., "search") appear with elem.type === "text"
- ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" );
- },
-
- // Position-in-collection
- "first": createPositionalPseudo(function() {
- return [ 0 ];
- }),
-
- "last": createPositionalPseudo(function( matchIndexes, length ) {
- return [ length - 1 ];
- }),
-
- "eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
- return [ argument < 0 ? argument + length : argument ];
- }),
-
- "even": createPositionalPseudo(function( matchIndexes, length ) {
- var i = 0;
- for ( ; i < length; i += 2 ) {
- matchIndexes.push( i );
- }
- return matchIndexes;
- }),
-
- "odd": createPositionalPseudo(function( matchIndexes, length ) {
- var i = 1;
- for ( ; i < length; i += 2 ) {
- matchIndexes.push( i );
- }
- return matchIndexes;
- }),
-
- "lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
- var i = argument < 0 ? argument + length : argument;
- for ( ; --i >= 0; ) {
- matchIndexes.push( i );
- }
- return matchIndexes;
- }),
-
- "gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
- var i = argument < 0 ? argument + length : argument;
- for ( ; ++i < length; ) {
- matchIndexes.push( i );
- }
- return matchIndexes;
- })
- }
-};
-
-Expr.pseudos["nth"] = Expr.pseudos["eq"];
-
-// Add button/input type pseudos
-for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
- Expr.pseudos[ i ] = createInputPseudo( i );
-}
-for ( i in { submit: true, reset: true } ) {
- Expr.pseudos[ i ] = createButtonPseudo( i );
-}
-
-// Easy API for creating new setFilters
-function setFilters() {}
-setFilters.prototype = Expr.filters = Expr.pseudos;
-Expr.setFilters = new setFilters();
-
-tokenize = Sizzle.tokenize = function( selector, parseOnly ) {
- var matched, match, tokens, type,
- soFar, groups, preFilters,
- cached = tokenCache[ selector + " " ];
-
- if ( cached ) {
- return parseOnly ? 0 : cached.slice( 0 );
- }
-
- soFar = selector;
- groups = [];
- preFilters = Expr.preFilter;
-
- while ( soFar ) {
-
- // Comma and first run
- if ( !matched || (match = rcomma.exec( soFar )) ) {
- if ( match ) {
- // Don't consume trailing commas as valid
- soFar = soFar.slice( match[0].length ) || soFar;
- }
- groups.push( (tokens = []) );
- }
-
- matched = false;
-
- // Combinators
- if ( (match = rcombinators.exec( soFar )) ) {
- matched = match.shift();
- tokens.push({
- value: matched,
- // Cast descendant combinators to space
- type: match[0].replace( rtrim, " " )
- });
- soFar = soFar.slice( matched.length );
- }
-
- // Filters
- for ( type in Expr.filter ) {
- if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
- (match = preFilters[ type ]( match ))) ) {
- matched = match.shift();
- tokens.push({
- value: matched,
- type: type,
- matches: match
- });
- soFar = soFar.slice( matched.length );
- }
- }
-
- if ( !matched ) {
- break;
- }
- }
-
- // Return the length of the invalid excess
- // if we're just parsing
- // Otherwise, throw an error or return tokens
- return parseOnly ?
- soFar.length :
- soFar ?
- Sizzle.error( selector ) :
- // Cache the tokens
- tokenCache( selector, groups ).slice( 0 );
-};
-
-function toSelector( tokens ) {
- var i = 0,
- len = tokens.length,
- selector = "";
- for ( ; i < len; i++ ) {
- selector += tokens[i].value;
- }
- return selector;
-}
-
-function addCombinator( matcher, combinator, base ) {
- var dir = combinator.dir,
- checkNonElements = base && dir === "parentNode",
- doneName = done++;
-
- return combinator.first ?
- // Check against closest ancestor/preceding element
- function( elem, context, xml ) {
- while ( (elem = elem[ dir ]) ) {
- if ( elem.nodeType === 1 || checkNonElements ) {
- return matcher( elem, context, xml );
- }
- }
- } :
-
- // Check against all ancestor/preceding elements
- function( elem, context, xml ) {
- var oldCache, uniqueCache, outerCache,
- newCache = [ dirruns, doneName ];
-
- // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching
- if ( xml ) {
- while ( (elem = elem[ dir ]) ) {
- if ( elem.nodeType === 1 || checkNonElements ) {
- if ( matcher( elem, context, xml ) ) {
- return true;
- }
- }
- }
- } else {
- while ( (elem = elem[ dir ]) ) {
- if ( elem.nodeType === 1 || checkNonElements ) {
- outerCache = elem[ expando ] || (elem[ expando ] = {});
-
- // Support: IE <9 only
- // Defend against cloned attroperties (jQuery gh-1709)
- uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {});
-
- if ( (oldCache = uniqueCache[ dir ]) &&
- 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[ dir ] = newCache;
-
- // A match means we're done; a fail means we have to keep checking
- if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) {
- return true;
- }
- }
- }
- }
- }
- };
-}
-
-function elementMatcher( matchers ) {
- return matchers.length > 1 ?
- function( elem, context, xml ) {
- var i = matchers.length;
- while ( i-- ) {
- if ( !matchers[i]( elem, context, xml ) ) {
- return false;
- }
- }
- return true;
- } :
- matchers[0];
-}
-
-function multipleContexts( selector, contexts, results ) {
- var i = 0,
- len = contexts.length;
- for ( ; i < len; i++ ) {
- Sizzle( selector, contexts[i], results );
- }
- return results;
-}
-
-function condense( unmatched, map, filter, context, xml ) {
- var elem,
- newUnmatched = [],
- i = 0,
- len = unmatched.length,
- mapped = map != null;
-
- for ( ; i < len; i++ ) {
- if ( (elem = unmatched[i]) ) {
- if ( !filter || filter( elem, context, xml ) ) {
- newUnmatched.push( elem );
- if ( mapped ) {
- map.push( i );
- }
- }
- }
- }
-
- return newUnmatched;
-}
-
-function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
- if ( postFilter && !postFilter[ expando ] ) {
- postFilter = setMatcher( postFilter );
- }
- if ( postFinder && !postFinder[ expando ] ) {
- postFinder = setMatcher( postFinder, postSelector );
- }
- return markFunction(function( seed, results, context, xml ) {
- var temp, i, elem,
- preMap = [],
- postMap = [],
- preexisting = results.length,
-
- // Get initial elements from seed or context
- elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
-
- // Prefilter to get matcher input, preserving a map for seed-results synchronization
- matcherIn = preFilter && ( seed || !selector ) ?
- condense( elems, preMap, preFilter, context, xml ) :
- elems,
-
- matcherOut = matcher ?
- // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
- postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
-
- // ...intermediate processing is necessary
- [] :
-
- // ...otherwise use results directly
- results :
- matcherIn;
-
- // Find primary matches
- if ( matcher ) {
- matcher( matcherIn, matcherOut, context, xml );
- }
-
- // Apply postFilter
- if ( postFilter ) {
- temp = condense( matcherOut, postMap );
- postFilter( temp, [], context, xml );
-
- // Un-match failing elements by moving them back to matcherIn
- i = temp.length;
- while ( i-- ) {
- if ( (elem = temp[i]) ) {
- matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
- }
- }
- }
-
- if ( seed ) {
- if ( postFinder || preFilter ) {
- if ( postFinder ) {
- // Get the final matcherOut by condensing this intermediate into postFinder contexts
- temp = [];
- i = matcherOut.length;
- while ( i-- ) {
- if ( (elem = matcherOut[i]) ) {
- // Restore matcherIn since elem is not yet a final match
- temp.push( (matcherIn[i] = elem) );
- }
- }
- postFinder( null, (matcherOut = []), temp, xml );
- }
-
- // Move matched elements from seed to results to keep them synchronized
- i = matcherOut.length;
- while ( i-- ) {
- if ( (elem = matcherOut[i]) &&
- (temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) {
-
- seed[temp] = !(results[temp] = elem);
- }
- }
- }
-
- // Add elements to results, through postFinder if defined
- } else {
- matcherOut = condense(
- matcherOut === results ?
- matcherOut.splice( preexisting, matcherOut.length ) :
- matcherOut
- );
- if ( postFinder ) {
- postFinder( null, results, matcherOut, xml );
- } else {
- push.apply( results, matcherOut );
- }
- }
- });
-}
-
-function matcherFromTokens( tokens ) {
- var checkContext, matcher, j,
- len = tokens.length,
- leadingRelative = Expr.relative[ tokens[0].type ],
- implicitRelative = leadingRelative || Expr.relative[" "],
- i = leadingRelative ? 1 : 0,
-
- // The foundational matcher ensures that elements are reachable from top-level context(s)
- matchContext = addCombinator( function( elem ) {
- return elem === checkContext;
- }, implicitRelative, true ),
- matchAnyContext = addCombinator( function( elem ) {
- return indexOf( checkContext, elem ) > -1;
- }, implicitRelative, true ),
- matchers = [ function( elem, context, xml ) {
- var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
- (checkContext = context).nodeType ?
- matchContext( elem, context, xml ) :
- matchAnyContext( elem, context, xml ) );
- // Avoid hanging onto element (issue #299)
- checkContext = null;
- return ret;
- } ];
-
- for ( ; i < len; i++ ) {
- if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
- matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
- } else {
- matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
-
- // Return special upon seeing a positional matcher
- if ( matcher[ expando ] ) {
- // Find the next relative operator (if any) for proper handling
- j = ++i;
- for ( ; j < len; j++ ) {
- if ( Expr.relative[ tokens[j].type ] ) {
- break;
- }
- }
- return setMatcher(
- i > 1 && elementMatcher( matchers ),
- i > 1 && toSelector(
- // If the preceding token was a descendant combinator, insert an implicit any-element `*`
- tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" })
- ).replace( rtrim, "$1" ),
- matcher,
- i < j && matcherFromTokens( tokens.slice( i, j ) ),
- j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
- j < len && toSelector( tokens )
- );
- }
- matchers.push( matcher );
- }
- }
-
- return elementMatcher( matchers );
-}
-
-function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
- var bySet = setMatchers.length > 0,
- byElement = elementMatchers.length > 0,
- superMatcher = function( seed, context, xml, results, outermost ) {
- var elem, j, matcher,
- matchedCount = 0,
- i = "0",
- unmatched = seed && [],
- setMatched = [],
- contextBackup = outermostContext,
- // We must always have either seed elements or outermost context
- elems = seed || byElement && Expr.find["TAG"]( "*", outermost ),
- // Use integer dirruns iff this is the outermost matcher
- dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1),
- len = elems.length;
-
- if ( outermost ) {
- outermostContext = context === document || context || outermost;
- }
-
- // Add elements passing elementMatchers directly to results
- // Support: IE<9, Safari
- // Tolerate NodeList properties (IE: "length"; Safari: ) matching elements by id
- for ( ; i !== len && (elem = elems[i]) != null; i++ ) {
- if ( byElement && elem ) {
- j = 0;
- if ( !context && elem.ownerDocument !== document ) {
- setDocument( elem );
- xml = !documentIsHTML;
- }
- while ( (matcher = elementMatchers[j++]) ) {
- if ( matcher( elem, context || document, xml) ) {
- results.push( elem );
- break;
- }
- }
- if ( outermost ) {
- dirruns = dirrunsUnique;
- }
- }
-
- // Track unmatched elements for set filters
- if ( bySet ) {
- // They will have gone through all possible matchers
- if ( (elem = !matcher && elem) ) {
- matchedCount--;
- }
-
- // Lengthen the array for every element, matched or not
- if ( seed ) {
- unmatched.push( elem );
- }
- }
- }
-
- // `i` is now the count of elements visited above, and adding it to `matchedCount`
- // makes the latter nonnegative.
- matchedCount += i;
-
- // Apply set filters to unmatched elements
- // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount`
- // equals `i`), unless we didn't visit _any_ elements in the above loop because we have
- // no element matchers and no seed.
- // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that
- // case, which will result in a "00" `matchedCount` that differs from `i` but is also
- // numerically zero.
- if ( bySet && i !== matchedCount ) {
- j = 0;
- while ( (matcher = setMatchers[j++]) ) {
- matcher( unmatched, setMatched, context, xml );
- }
-
- if ( seed ) {
- // Reintegrate element matches to eliminate the need for sorting
- if ( matchedCount > 0 ) {
- while ( i-- ) {
- if ( !(unmatched[i] || setMatched[i]) ) {
- setMatched[i] = pop.call( results );
- }
- }
- }
-
- // Discard index placeholder values to get only actual matches
- setMatched = condense( setMatched );
- }
-
- // Add matches to results
- push.apply( results, setMatched );
-
- // Seedless set matches succeeding multiple successful matchers stipulate sorting
- if ( outermost && !seed && setMatched.length > 0 &&
- ( matchedCount + setMatchers.length ) > 1 ) {
-
- Sizzle.uniqueSort( results );
- }
- }
-
- // Override manipulation of globals by nested matchers
- if ( outermost ) {
- dirruns = dirrunsUnique;
- outermostContext = contextBackup;
- }
-
- return unmatched;
- };
-
- return bySet ?
- markFunction( superMatcher ) :
- superMatcher;
-}
-
-compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) {
- var i,
- setMatchers = [],
- elementMatchers = [],
- cached = compilerCache[ selector + " " ];
-
- if ( !cached ) {
- // Generate a function of recursive functions that can be used to check each element
- if ( !match ) {
- match = tokenize( selector );
- }
- i = match.length;
- while ( i-- ) {
- cached = matcherFromTokens( match[i] );
- if ( cached[ expando ] ) {
- setMatchers.push( cached );
- } else {
- elementMatchers.push( cached );
- }
- }
-
- // Cache the compiled function
- cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
-
- // Save selector and tokenization
- cached.selector = selector;
- }
- return cached;
-};
-
-/**
- * A low-level selection function that works with Sizzle's compiled
- * selector functions
- * @param {String|Function} selector A selector or a pre-compiled
- * selector function built with Sizzle.compile
- * @param {Element} context
- * @param {Array} [results]
- * @param {Array} [seed] A set of elements to match against
- */
-select = Sizzle.select = function( selector, context, results, seed ) {
- var i, tokens, token, type, find,
- compiled = typeof selector === "function" && selector,
- match = !seed && tokenize( (selector = compiled.selector || selector) );
-
- results = results || [];
-
- // Try to minimize operations if there is only one selector in the list and no seed
- // (the latter of which guarantees us context)
- if ( match.length === 1 ) {
-
- // Reduce context if the leading compound selector is an ID
- tokens = match[0] = match[0].slice( 0 );
- if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
- support.getById && context.nodeType === 9 && documentIsHTML &&
- Expr.relative[ tokens[1].type ] ) {
-
- context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
- if ( !context ) {
- return results;
-
- // Precompiled matchers will still verify ancestry, so step up a level
- } else if ( compiled ) {
- context = context.parentNode;
- }
-
- selector = selector.slice( tokens.shift().value.length );
- }
-
- // Fetch a seed set for right-to-left matching
- i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
- while ( i-- ) {
- token = tokens[i];
-
- // Abort if we hit a combinator
- if ( Expr.relative[ (type = token.type) ] ) {
- break;
- }
- if ( (find = Expr.find[ type ]) ) {
- // Search, expanding context for leading sibling combinators
- if ( (seed = find(
- token.matches[0].replace( runescape, funescape ),
- rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context
- )) ) {
-
- // If seed is empty or no tokens remain, we can return early
- tokens.splice( i, 1 );
- selector = seed.length && toSelector( tokens );
- if ( !selector ) {
- push.apply( results, seed );
- return results;
- }
-
- break;
- }
- }
- }
- }
-
- // Compile and execute a filtering function if one is not provided
- // Provide `match` to avoid retokenization if we modified the selector above
- ( compiled || compile( selector, match ) )(
- seed,
- context,
- !documentIsHTML,
- results,
- !context || rsibling.test( selector ) && testContext( context.parentNode ) || context
- );
- return results;
-};
-
-// One-time assignments
-
-// Sort stability
-support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
-
-// Support: Chrome 14-35+
-// Always assume duplicates if they aren't passed to the comparison function
-support.detectDuplicates = !!hasDuplicate;
-
-// Initialize against the default document
-setDocument();
-
-// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
-// Detached nodes confoundingly follow *each other*
-support.sortDetached = assert(function( div1 ) {
- // Should return 1, but returns 4 (following)
- return div1.compareDocumentPosition( document.createElement("div") ) & 1;
+(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["jsQR"] = factory();
+ else
+ root["jsQR"] = factory();
+})(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 binarizer_1 = __webpack_require__(1);
+ var locator_1 = __webpack_require__(3);
+ var extractor_1 = __webpack_require__(4);
+ var decoder_1 = __webpack_require__(9);
+ var bitmatrix_1 = __webpack_require__(2);
+ var binarizeImage = binarizer_1.binarize;
+ exports.binarizeImage = binarizeImage;
+ var locateQRInBinaryImage = locator_1.locate;
+ exports.locateQRInBinaryImage = locateQRInBinaryImage;
+ var extractQRFromBinaryImage = extractor_1.extract;
+ exports.extractQRFromBinaryImage = extractQRFromBinaryImage;
+ function decodeQR(matrix) {
+ return byteArrayToString(decoder_1.decode(matrix));
+ }
+ exports.decodeQR = decodeQR;
+ // return bytes.reduce((p, b) => p + String.fromCharCode(b), "");
+ function byteArrayToString(bytes) {
+ var str = "";
+ if (bytes != null && bytes != undefined) {
+ for (var i = 0; i < bytes.length; i++) {
+ str += String.fromCharCode(bytes[i]);
+ }
+ }
+ return str;
+ }
+ function createBitMatrix(data, width) {
+ return new bitmatrix_1.BitMatrix(data, width);
+ }
+ exports.createBitMatrix = createBitMatrix;
+ function decodeQRFromImage(data, width, height) {
+ return byteArrayToString(decodeQRFromImageAsByteArray(data, width, height));
+ }
+ exports.decodeQRFromImage = decodeQRFromImage;
+ function decodeQRFromImageAsByteArray(data, width, height) {
+ var binarizedImage = binarizeImage(data, width, height);
+ var location = locator_1.locate(binarizedImage);
+ if (!location) {
+ return null;
+ }
+ var rawQR = extractor_1.extract(binarizedImage, location);
+ if (!rawQR) {
+ return null;
+ }
+ return decoder_1.decode(rawQR);
+ }
+ exports.decodeQRFromImageAsByteArray = decodeQRFromImageAsByteArray;
+
+
+/***/ },
+/* 1 */
+/***/ function(module, exports, __webpack_require__) {
+
+ "use strict";
+ var bitmatrix_1 = __webpack_require__(2);
+ // Magic Constants
+ var BLOCK_SIZE_POWER = 3;
+ var BLOCK_SIZE = 1 << BLOCK_SIZE_POWER;
+ var BLOCK_SIZE_MASK = BLOCK_SIZE - 1;
+ var MIN_DYNAMIC_RANGE = 24;
+ function calculateBlackPoints(luminances, subWidth, subHeight, width, height) {
+ var blackPoints = new Array(subHeight);
+ for (var i = 0; i < subHeight; i++) {
+ blackPoints[i] = new Array(subWidth);
+ }
+ for (var y = 0; y < subHeight; y++) {
+ var yoffset = y << BLOCK_SIZE_POWER;
+ var maxYOffset = height - BLOCK_SIZE;
+ if (yoffset > maxYOffset) {
+ yoffset = maxYOffset;
+ }
+ for (var x = 0; x < subWidth; x++) {
+ var xoffset = x << BLOCK_SIZE_POWER;
+ var maxXOffset = width - BLOCK_SIZE;
+ if (xoffset > maxXOffset) {
+ xoffset = maxXOffset;
+ }
+ var sum = 0;
+ var min = 0xFF;
+ var max = 0;
+ for (var yy = 0, offset = yoffset * width + xoffset; yy < BLOCK_SIZE; yy++, offset += width) {
+ for (var xx = 0; xx < BLOCK_SIZE; xx++) {
+ var pixel = luminances[offset + xx] & 0xFF;
+ // still looking for good contrast
+ sum += pixel;
+ if (pixel < min) {
+ min = pixel;
+ }
+ if (pixel > max) {
+ max = pixel;
+ }
+ }
+ // short-circuit min/max tests once dynamic range is met
+ if (max - min > MIN_DYNAMIC_RANGE) {
+ // finish the rest of the rows quickly
+ for (yy++, offset += width; yy < BLOCK_SIZE; yy++, offset += width) {
+ for (var xx = 0; xx < BLOCK_SIZE; xx++) {
+ sum += luminances[offset + xx] & 0xFF;
+ }
+ }
+ }
+ }
+ // The default estimate is the average of the values in the block.
+ var average = sum >> (BLOCK_SIZE_POWER * 2);
+ if (max - min <= MIN_DYNAMIC_RANGE) {
+ // If variation within the block is low, assume this is a block with only light or only
+ // dark pixels. In that case we do not want to use the average, as it would divide this
+ // low contrast area into black and white pixels, essentially creating data out of noise.
+ //
+ // The default assumption is that the block is light/background. Since no estimate for
+ // the level of dark pixels exists locally, use half the min for the block.
+ average = min >> 1;
+ if (y > 0 && x > 0) {
+ // Correct the "white background" assumption for blocks that have neighbors by comparing
+ // the pixels in this block to the previously calculated black points. This is based on
+ // the fact that dark barcode symbology is always surrounded by some amount of light
+ // background for which reasonable black point estimates were made. The bp estimated at
+ // the boundaries is used for the interior.
+ // The (min < bp) is arbitrary but works better than other heuristics that were tried.
+ var averageNeighborBlackPoint = (blackPoints[y - 1][x] + (2 * blackPoints[y][x - 1]) + blackPoints[y - 1][x - 1]) >> 2;
+ if (min < averageNeighborBlackPoint) {
+ average = averageNeighborBlackPoint;
+ }
+ }
+ }
+ blackPoints[y][x] = average;
+ }
+ }
+ return blackPoints;
+ }
+ function calculateThresholdForBlock(luminances, subWidth, subHeight, width, height, blackPoints) {
+ function cap(value, min, max) {
+ return value < min ? min : value > max ? max : value;
+ }
+ // var outArray = new Array(width * height);
+ var outMatrix = bitmatrix_1.BitMatrix.createEmpty(width, height);
+ function thresholdBlock(luminances, xoffset, yoffset, threshold, stride) {
+ var offset = (yoffset * stride) + xoffset;
+ for (var y = 0; y < BLOCK_SIZE; y++, offset += stride) {
+ for (var x = 0; x < BLOCK_SIZE; x++) {
+ var pixel = luminances[offset + x] & 0xff;
+ // Comparison needs to be <= so that black == 0 pixels are black even if the threshold is 0.
+ outMatrix.set(xoffset + x, yoffset + y, pixel <= threshold);
+ }
+ }
+ }
+ for (var y = 0; y < subHeight; y++) {
+ var yoffset = y << BLOCK_SIZE_POWER;
+ var maxYOffset = height - BLOCK_SIZE;
+ if (yoffset > maxYOffset) {
+ yoffset = maxYOffset;
+ }
+ for (var x = 0; x < subWidth; x++) {
+ var xoffset = x << BLOCK_SIZE_POWER;
+ var maxXOffset = width - BLOCK_SIZE;
+ if (xoffset > maxXOffset) {
+ xoffset = maxXOffset;
+ }
+ var left = cap(x, 2, subWidth - 3);
+ var top = cap(y, 2, subHeight - 3);
+ var sum = 0;
+ for (var z = -2; z <= 2; z++) {
+ var blackRow = blackPoints[top + z];
+ sum += blackRow[left - 2];
+ sum += blackRow[left - 1];
+ sum += blackRow[left];
+ sum += blackRow[left + 1];
+ sum += blackRow[left + 2];
+ }
+ var average = sum / 25;
+ thresholdBlock(luminances, xoffset, yoffset, average, width);
+ }
+ }
+ return outMatrix;
+ }
+ function binarize(data, width, height) {
+ if (data.length !== width * height * 4) {
+ throw new Error("Binarizer data.length != width * height * 4");
+ }
+ var gsArray = new Array(width * height);
+ for (var x = 0; x < width; x++) {
+ for (var y = 0; y < height; y++) {
+ var startIndex = (y * width + x) * 4;
+ var r = data[startIndex];
+ var g = data[startIndex + 1];
+ var b = data[startIndex + 2];
+ // Magic lumosity constants
+ var lum = 0.2126 * r + 0.7152 * g + 0.0722 * b;
+ gsArray[y * width + x] = lum;
+ }
+ }
+ var subWidth = width >> BLOCK_SIZE_POWER;
+ if ((width & BLOCK_SIZE_MASK) != 0) {
+ subWidth++;
+ }
+ var subHeight = height >> BLOCK_SIZE_POWER;
+ if ((height & BLOCK_SIZE_MASK) != 0) {
+ subHeight++;
+ }
+ var blackPoints = calculateBlackPoints(gsArray, subWidth, subHeight, width, height);
+ return calculateThresholdForBlock(gsArray, subWidth, subHeight, width, height, blackPoints);
+ }
+ exports.binarize = binarize;
+
+
+/***/ },
+/* 2 */
+/***/ function(module, exports) {
+
+ "use strict";
+ var BitMatrix = (function () {
+ function BitMatrix(data, width) {
+ this.width = width;
+ this.height = data.length / width;
+ this.data = data;
+ }
+ BitMatrix.createEmpty = function (width, height) {
+ var data = new Array(width * height);
+ for (var i = 0; i < data.length; i++) {
+ data[i] = false;
+ }
+ return new BitMatrix(data, width);
+ };
+ BitMatrix.prototype.get = function (x, y) {
+ return this.data[y * this.width + x];
+ };
+ BitMatrix.prototype.set = function (x, y, v) {
+ this.data[y * this.width + x] = v;
+ };
+ BitMatrix.prototype.copyBit = function (x, y, versionBits) {
+ return this.get(x, y) ? (versionBits << 1) | 0x1 : versionBits << 1;
+ };
+ BitMatrix.prototype.setRegion = function (left, top, width, height) {
+ var right = left + width;
+ var bottom = top + height;
+ for (var y = top; y < bottom; y++) {
+ for (var x = left; x < right; x++) {
+ this.set(x, y, true);
+ }
+ }
+ };
+ BitMatrix.prototype.mirror = function () {
+ for (var x = 0; x < this.width; x++) {
+ for (var y = x + 1; y < this.height; y++) {
+ if (this.get(x, y) != this.get(y, x)) {
+ this.set(x, y, !this.get(x, y));
+ this.set(y, x, !this.get(y, x));
+ }
+ }
+ }
+ };
+ return BitMatrix;
+ }());
+ exports.BitMatrix = BitMatrix;
+
+
+/***/ },
+/* 3 */
+/***/ function(module, exports) {
+
+ "use strict";
+ var CENTER_QUORUM = 2;
+ var MIN_SKIP = 3;
+ var MAX_MODULES = 57;
+ var INTEGER_MATH_SHIFT = 8;
+ var FinderPattern = (function () {
+ function FinderPattern(x, y, estimatedModuleSize, count) {
+ this.x = x;
+ this.y = y;
+ this.estimatedModuleSize = estimatedModuleSize;
+ if (count == null) {
+ this.count = 1;
+ }
+ else {
+ this.count = count;
+ }
+ }
+ FinderPattern.prototype.aboutEquals = function (moduleSize, i, j) {
+ if (Math.abs(i - this.y) <= moduleSize && Math.abs(j - this.x) <= moduleSize) {
+ var moduleSizeDiff = Math.abs(moduleSize - this.estimatedModuleSize);
+ return moduleSizeDiff <= 1.0 || moduleSizeDiff <= this.estimatedModuleSize;
+ }
+ return false;
+ };
+ FinderPattern.prototype.combineEstimate = function (i, j, newModuleSize) {
+ var combinedCount = this.count + 1;
+ var combinedX = (this.count * this.x + j) / combinedCount;
+ var combinedY = (this.count * this.y + i) / combinedCount;
+ var combinedModuleSize = (this.count * this.estimatedModuleSize + newModuleSize) / combinedCount;
+ return new FinderPattern(combinedX, combinedY, combinedModuleSize, combinedCount);
+ };
+ return FinderPattern;
+ }());
+ function foundPatternCross(stateCount) {
+ var totalModuleSize = 0;
+ for (var i = 0; i < 5; i++) {
+ var count = stateCount[i];
+ if (count === 0)
+ return false;
+ totalModuleSize += count;
+ }
+ if (totalModuleSize < 7)
+ return false;
+ var moduleSize = (totalModuleSize << INTEGER_MATH_SHIFT) / 7;
+ var maxVariance = moduleSize / 2;
+ // Allow less than 50% variance from 1-1-3-1-1 proportions
+ return Math.abs(moduleSize - (stateCount[0] << INTEGER_MATH_SHIFT)) < maxVariance &&
+ Math.abs(moduleSize - (stateCount[1] << INTEGER_MATH_SHIFT)) < maxVariance &&
+ Math.abs(3 * moduleSize - (stateCount[2] << INTEGER_MATH_SHIFT)) < 3 * maxVariance &&
+ Math.abs(moduleSize - (stateCount[3] << INTEGER_MATH_SHIFT)) < maxVariance &&
+ Math.abs(moduleSize - (stateCount[4] << INTEGER_MATH_SHIFT)) < maxVariance;
+ }
+ function centerFromEnd(stateCount, end) {
+ var result = (end - stateCount[4] - stateCount[3]) - stateCount[2] / 2;
+ // Fix this.
+ if (result !== result) {
+ return null;
+ }
+ return result;
+ }
+ function distance(pattern1, pattern2) {
+ var a = pattern1.x - pattern2.x;
+ var b = pattern1.y - pattern2.y;
+ return Math.sqrt(a * a + b * b);
+ }
+ function crossProductZ(pointA, pointB, pointC) {
+ var bX = pointB.x;
+ var bY = pointB.y;
+ return ((pointC.x - bX) * (pointA.y - bY)) - ((pointC.y - bY) * (pointA.x - bX));
+ }
+ function ReorderFinderPattern(patterns) {
+ // Find distances between pattern centers
+ var zeroOneDistance = distance(patterns[0], patterns[1]);
+ var oneTwoDistance = distance(patterns[1], patterns[2]);
+ var zeroTwoDistance = distance(patterns[0], patterns[2]);
+ var pointA, pointB, pointC;
+ // Assume one closest to other two is B; A and C will just be guesses at first
+ if (oneTwoDistance >= zeroOneDistance && oneTwoDistance >= zeroTwoDistance) {
+ pointB = patterns[0];
+ pointA = patterns[1];
+ pointC = patterns[2];
+ }
+ else if (zeroTwoDistance >= oneTwoDistance && zeroTwoDistance >= zeroOneDistance) {
+ pointB = patterns[1];
+ pointA = patterns[0];
+ pointC = patterns[2];
+ }
+ else {
+ pointB = patterns[2];
+ pointA = patterns[0];
+ pointC = patterns[1];
+ }
+ // Use cross product to figure out whether A and C are correct or flipped.
+ // This asks whether BC x BA has a positive z component, which is the arrangement
+ // we want for A, B, C. If it's negative, then we've got it flipped around and
+ // should swap A and C.
+ if (crossProductZ(pointA, pointB, pointC) < 0) {
+ var temp = pointA;
+ pointA = pointC;
+ pointC = temp;
+ }
+ return {
+ bottomLeft: { x: pointA.x, y: pointA.y },
+ topLeft: { x: pointB.x, y: pointB.y },
+ topRight: { x: pointC.x, y: pointC.y }
+ };
+ }
+ function locate(matrix) {
+ // Global state :(
+ var possibleCenters = [];
+ var hasSkipped = false;
+ function get(x, y) {
+ x = Math.floor(x);
+ y = Math.floor(y);
+ return matrix.get(x, y);
+ }
+ // Methods
+ function crossCheckDiagonal(startI, centerJ, maxCount, originalStateCountTotal) {
+ var maxI = matrix.height;
+ var maxJ = matrix.width;
+ var stateCount = [0, 0, 0, 0, 0];
+ // Start counting up, left from center finding black center mass
+ var i = 0;
+ while (startI - i >= 0 && get(centerJ - i, startI - i)) {
+ stateCount[2]++;
+ i++;
+ }
+ if ((startI - i < 0) || (centerJ - i < 0)) {
+ return false;
+ }
+ // Continue up, left finding white space
+ while ((startI - i >= 0) && (centerJ - i >= 0) && !get(centerJ - i, startI - i) && stateCount[1] <= maxCount) {
+ stateCount[1]++;
+ i++;
+ }
+ // If already too many modules in this state or ran off the edge:
+ if ((startI - i < 0) || (centerJ - i < 0) || stateCount[1] > maxCount) {
+ return false;
+ }
+ // Continue up, left finding black border
+ while ((startI - i >= 0) && (centerJ - i >= 0) && get(centerJ - i, startI - i) && stateCount[0] <= maxCount) {
+ stateCount[0]++;
+ i++;
+ }
+ if (stateCount[0] > maxCount) {
+ return false;
+ }
+ // Now also count down, right from center
+ i = 1;
+ while ((startI + i < maxI) && (centerJ + i < maxJ) && get(centerJ + i, startI + i)) {
+ stateCount[2]++;
+ i++;
+ }
+ // Ran off the edge?
+ if ((startI + i >= maxI) || (centerJ + i >= maxJ)) {
+ return false;
+ }
+ while ((startI + i < maxI) && (centerJ + i < maxJ) && !get(centerJ + i, startI + i) && stateCount[3] < maxCount) {
+ stateCount[3]++;
+ i++;
+ }
+ if ((startI + i >= maxI) || (centerJ + i >= maxJ) || stateCount[3] >= maxCount) {
+ return false;
+ }
+ while ((startI + i < maxI) && (centerJ + i < maxJ) && get(centerJ + i, startI + i) && stateCount[4] < maxCount) {
+ stateCount[4]++;
+ i++;
+ }
+ if (stateCount[4] >= maxCount) {
+ return false;
+ }
+ // If we found a finder-pattern-like section, but its size is more than 100% different than
+ // the original, assume it's a false positive
+ var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];
+ return Math.abs(stateCountTotal - originalStateCountTotal) < 2 * originalStateCountTotal &&
+ foundPatternCross(stateCount);
+ }
+ function crossCheckVertical(startI, centerJ, maxCount, originalStateCountTotal) {
+ var maxI = matrix.height;
+ var stateCount = [0, 0, 0, 0, 0];
+ // Start counting up from center
+ var i = startI;
+ while (i >= 0 && get(centerJ, i)) {
+ stateCount[2]++;
+ i--;
+ }
+ if (i < 0) {
+ return null;
+ }
+ while (i >= 0 && !get(centerJ, i) && stateCount[1] <= maxCount) {
+ stateCount[1]++;
+ i--;
+ }
+ // If already too many modules in this state or ran off the edge:
+ if (i < 0 || stateCount[1] > maxCount) {
+ return null;
+ }
+ while (i >= 0 && get(centerJ, i) && stateCount[0] <= maxCount) {
+ stateCount[0]++;
+ i--;
+ }
+ if (stateCount[0] > maxCount) {
+ return null;
+ }
+ // Now also count down from center
+ i = startI + 1;
+ while (i < maxI && get(centerJ, i)) {
+ stateCount[2]++;
+ i++;
+ }
+ if (i == maxI) {
+ return null;
+ }
+ while (i < maxI && !get(centerJ, i) && stateCount[3] < maxCount) {
+ stateCount[3]++;
+ i++;
+ }
+ if (i == maxI || stateCount[3] >= maxCount) {
+ return null;
+ }
+ while (i < maxI && get(centerJ, i) && stateCount[4] < maxCount) {
+ stateCount[4]++;
+ i++;
+ }
+ if (stateCount[4] >= maxCount) {
+ return null;
+ }
+ // If we found a finder-pattern-like section, but its size is more than 40% different than
+ // the original, assume it's a false positive
+ var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];
+ if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal) {
+ return null;
+ }
+ return foundPatternCross(stateCount) ? centerFromEnd(stateCount, i) : null;
+ }
+ function haveMultiplyConfirmedCenters() {
+ var confirmedCount = 0;
+ var totalModuleSize = 0;
+ var max = possibleCenters.length;
+ possibleCenters.forEach(function (pattern) {
+ if (pattern.count >= CENTER_QUORUM) {
+ confirmedCount++;
+ totalModuleSize += pattern.estimatedModuleSize;
+ }
+ });
+ if (confirmedCount < 3) {
+ return false;
+ }
+ // OK, we have at least 3 confirmed centers, but, it's possible that one is a "false positive"
+ // and that we need to keep looking. We detect this by asking if the estimated module sizes
+ // vary too much. We arbitrarily say that when the total deviation from average exceeds
+ // 5% of the total module size estimates, it's too much.
+ var average = totalModuleSize / max;
+ var totalDeviation = 0;
+ for (var i = 0; i < max; i++) {
+ var pattern = possibleCenters[i];
+ totalDeviation += Math.abs(pattern.estimatedModuleSize - average);
+ }
+ return totalDeviation <= 0.05 * totalModuleSize;
+ }
+ function crossCheckHorizontal(startJ, centerI, maxCount, originalStateCountTotal) {
+ var maxJ = matrix.width;
+ var stateCount = [0, 0, 0, 0, 0];
+ var j = startJ;
+ while (j >= 0 && get(j, centerI)) {
+ stateCount[2]++;
+ j--;
+ }
+ if (j < 0) {
+ return null;
+ }
+ while (j >= 0 && !get(j, centerI) && stateCount[1] <= maxCount) {
+ stateCount[1]++;
+ j--;
+ }
+ if (j < 0 || stateCount[1] > maxCount) {
+ return null;
+ }
+ while (j >= 0 && get(j, centerI) && stateCount[0] <= maxCount) {
+ stateCount[0]++;
+ j--;
+ }
+ if (stateCount[0] > maxCount) {
+ return null;
+ }
+ j = startJ + 1;
+ while (j < maxJ && get(j, centerI)) {
+ stateCount[2]++;
+ j++;
+ }
+ if (j == maxJ) {
+ return null;
+ }
+ while (j < maxJ && !get(j, centerI) && stateCount[3] < maxCount) {
+ stateCount[3]++;
+ j++;
+ }
+ if (j == maxJ || stateCount[3] >= maxCount) {
+ return null;
+ }
+ while (j < maxJ && get(j, centerI) && stateCount[4] < maxCount) {
+ stateCount[4]++;
+ j++;
+ }
+ if (stateCount[4] >= maxCount) {
+ return null;
+ }
+ // If we found a finder-pattern-like section, but its size is significantly different than
+ // the original, assume it's a false positive
+ var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];
+ if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal) {
+ return null;
+ }
+ return foundPatternCross(stateCount) ? centerFromEnd(stateCount, j) : null;
+ }
+ function handlePossibleCenter(stateCount, i, j, pureBarcode) {
+ var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];
+ var centerJ = centerFromEnd(stateCount, j);
+ if (centerJ == null)
+ return false;
+ var centerI = crossCheckVertical(i, Math.floor(centerJ), stateCount[2], stateCountTotal);
+ if (centerI != null) {
+ // Re-cross check
+ centerJ = crossCheckHorizontal(Math.floor(centerJ), Math.floor(centerI), stateCount[2], stateCountTotal);
+ if (centerJ != null && (!pureBarcode || crossCheckDiagonal(Math.floor(centerI), Math.floor(centerJ), stateCount[2], stateCountTotal))) {
+ var estimatedModuleSize = stateCountTotal / 7;
+ var found = false;
+ for (var index = 0; index < possibleCenters.length; index++) {
+ var center = possibleCenters[index];
+ // Look for about the same center and module size:
+ if (center.aboutEquals(estimatedModuleSize, centerI, centerJ)) {
+ possibleCenters.splice(index, 1, center.combineEstimate(centerI, centerJ, estimatedModuleSize));
+ found = true;
+ break;
+ }
+ }
+ if (!found) {
+ // var point = new FinderPattern(centerJ.Value, centerI.Value, estimatedModuleSize);
+ var point = new FinderPattern(centerJ, centerI, estimatedModuleSize);
+ possibleCenters.push(point);
+ }
+ return true;
+ }
+ }
+ return false;
+ }
+ function findRowSkip() {
+ var max = possibleCenters.length;
+ if (max <= 1) {
+ return 0;
+ }
+ var firstConfirmedCenter = null;
+ possibleCenters.forEach(function (center) {
+ if (center.count >= CENTER_QUORUM) {
+ if (firstConfirmedCenter == null) {
+ firstConfirmedCenter = center;
+ }
+ else {
+ // We have two confirmed centers
+ // How far down can we skip before resuming looking for the next
+ // pattern? In the worst case, only the difference between the
+ // difference in the x / y coordinates of the two centers.
+ // This is the case where you find top left last.
+ hasSkipped = true;
+ //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
+ return Math.floor(Math.abs(firstConfirmedCenter.x - center.x) - Math.abs(firstConfirmedCenter.y - center.y)) / 2;
+ }
+ }
+ });
+ return 0;
+ }
+ function selectBestPatterns() {
+ var startSize = possibleCenters.length;
+ if (startSize < 3) {
+ // Couldn't find enough finder patterns
+ return null;
+ }
+ // Filter outlier possibilities whose module size is too different
+ if (startSize > 3) {
+ // But we can only afford to do so if we have at least 4 possibilities to choose from
+ var totalModuleSize = 0;
+ var square = 0;
+ possibleCenters.forEach(function (center) {
+ var size = center.estimatedModuleSize;
+ totalModuleSize += size;
+ square += size * size;
+ });
+ var average = totalModuleSize / startSize;
+ var stdDev = Math.sqrt(square / startSize - average * average);
+ //possibleCenters.Sort(new FurthestFromAverageComparator(average));
+ possibleCenters.sort(function (x, y) {
+ var dA = Math.abs(y.estimatedModuleSize - average);
+ var dB = Math.abs(x.estimatedModuleSize - average);
+ return dA < dB ? -1 : dA == dB ? 0 : 1;
+ });
+ var limit = Math.max(0.2 * average, stdDev);
+ for (var i = 0; i < possibleCenters.length && possibleCenters.length > 3; i++) {
+ var pattern = possibleCenters[i];
+ if (Math.abs(pattern.estimatedModuleSize - average) > limit) {
+ possibleCenters.splice(i, 1);
+ ///possibleCenters.RemoveAt(i);
+ i--;
+ }
+ }
+ }
+ if (possibleCenters.length > 3) {
+ // Throw away all but those first size candidate points we found.
+ var totalModuleSize = 0;
+ possibleCenters.forEach(function (possibleCenter) {
+ totalModuleSize += possibleCenter.estimatedModuleSize;
+ });
+ var average = totalModuleSize / possibleCenters.length;
+ // possibleCenters.Sort(new CenterComparator(average));
+ possibleCenters.sort(function (x, y) {
+ if (y.count === x.count) {
+ var dA = Math.abs(y.estimatedModuleSize - average);
+ var dB = Math.abs(x.estimatedModuleSize - average);
+ return dA < dB ? 1 : dA == dB ? 0 : -1;
+ }
+ return y.count - x.count;
+ });
+ //possibleCenters.subList(3, possibleCenters.Count).clear();
+ ///possibleCenters = possibleCenters.GetRange(0, 3);
+ possibleCenters = possibleCenters.slice(0, 3);
+ }
+ return [possibleCenters[0], possibleCenters[1], possibleCenters[2]];
+ }
+ var pureBarcode = false;
+ var maxI = matrix.height;
+ var maxJ = matrix.width;
+ var iSkip = Math.floor((3 * maxI) / (4 * MAX_MODULES));
+ if (iSkip < MIN_SKIP || false) {
+ iSkip = MIN_SKIP;
+ }
+ var done = false;
+ var stateCount = [0, 0, 0, 0, 0];
+ for (var i = iSkip - 1; i < maxI && !done; i += iSkip) {
+ stateCount = [0, 0, 0, 0, 0];
+ var currentState = 0;
+ for (var j = 0; j < maxJ; j++) {
+ if (get(j, i)) {
+ // Black pixel
+ if ((currentState & 1) === 1) {
+ currentState++;
+ }
+ stateCount[currentState]++;
+ }
+ else {
+ // White pixel
+ if ((currentState & 1) === 0) {
+ // Counting black pixels
+ if (currentState === 4) {
+ // A winner?
+ if (foundPatternCross(stateCount)) {
+ // Yes
+ var confirmed = handlePossibleCenter(stateCount, i, j, pureBarcode);
+ if (confirmed) {
+ // Start examining every other line. Checking each line turned out to be too
+ // expensive and didn't improve performance.
+ iSkip = 2;
+ if (hasSkipped) {
+ done = haveMultiplyConfirmedCenters();
+ }
+ else {
+ var rowSkip = findRowSkip();
+ if (rowSkip > stateCount[2]) {
+ // Skip rows between row of lower confirmed center
+ // and top of presumed third confirmed center
+ // but back up a bit to get a full chance of detecting
+ // it, entire width of center of finder pattern
+ // Skip by rowSkip, but back off by stateCount[2] (size of last center
+ // of pattern we saw) to be conservative, and also back off by iSkip which
+ // is about to be re-added
+ i += rowSkip - stateCount[2] - iSkip;
+ j = maxJ - 1;
+ }
+ }
+ }
+ else {
+ stateCount = [stateCount[2], stateCount[3], stateCount[4], 1, 0];
+ currentState = 3;
+ continue;
+ }
+ // Clear state to start looking again
+ stateCount = [0, 0, 0, 0, 0];
+ currentState = 0;
+ }
+ else {
+ stateCount = [stateCount[2], stateCount[3], stateCount[4], 1, 0];
+ currentState = 3;
+ }
+ }
+ else {
+ // Should I really have copy/pasted this fuckery?
+ stateCount[++currentState]++;
+ }
+ }
+ else {
+ // Counting the white pixels
+ stateCount[currentState]++;
+ }
+ }
+ }
+ if (foundPatternCross(stateCount)) {
+ var confirmed = handlePossibleCenter(stateCount, i, maxJ, pureBarcode);
+ if (confirmed) {
+ iSkip = stateCount[0];
+ if (hasSkipped) {
+ // Found a third one
+ done = haveMultiplyConfirmedCenters();
+ }
+ }
+ }
+ }
+ var patternInfo = selectBestPatterns();
+ if (!patternInfo)
+ return null;
+ return ReorderFinderPattern(patternInfo);
+ }
+ exports.locate = locate;
+
+
+/***/ },
+/* 4 */
+/***/ function(module, exports, __webpack_require__) {
+
+ "use strict";
+ ///
+ var alignment_finder_1 = __webpack_require__(5);
+ var perspective_transform_1 = __webpack_require__(7);
+ var version_1 = __webpack_require__(8);
+ var bitmatrix_1 = __webpack_require__(2);
+ var helpers_1 = __webpack_require__(6);
+ function checkAndNudgePoints(width, height, points) {
+ // Check and nudge points from start until we see some that are OK:
+ var nudged = true;
+ for (var offset = 0; offset < points.length && nudged; offset += 2) {
+ var x = Math.floor(points[offset]);
+ var y = Math.floor(points[offset + 1]);
+ if (x < -1 || x > width || y < -1 || y > height) {
+ throw new Error();
+ }
+ nudged = false;
+ if (x == -1) {
+ points[offset] = 0;
+ nudged = true;
+ }
+ else if (x == width) {
+ points[offset] = width - 1;
+ nudged = true;
+ }
+ if (y == -1) {
+ points[offset + 1] = 0;
+ nudged = true;
+ }
+ else if (y == height) {
+ points[offset + 1] = height - 1;
+ nudged = true;
+ }
+ }
+ // Check and nudge points from end:
+ nudged = true;
+ for (var offset = points.length - 2; offset >= 0 && nudged; offset -= 2) {
+ var x = Math.floor(points[offset]);
+ var y = Math.floor(points[offset + 1]);
+ if (x < -1 || x > width || y < -1 || y > height) {
+ throw new Error();
+ }
+ nudged = false;
+ if (x == -1) {
+ points[offset] = 0;
+ nudged = true;
+ }
+ else if (x == width) {
+ points[offset] = width - 1;
+ nudged = true;
+ }
+ if (y == -1) {
+ points[offset + 1] = 0;
+ nudged = true;
+ }
+ else if (y == height) {
+ points[offset + 1] = height - 1;
+ nudged = true;
+ }
+ }
+ return points;
+ }
+ function bitArrayFromImage(image, dimension, transform) {
+ if (dimension <= 0) {
+ return null;
+ }
+ var bits = bitmatrix_1.BitMatrix.createEmpty(dimension, dimension);
+ var points = new Array(dimension << 1);
+ for (var y = 0; y < dimension; y++) {
+ var max = points.length;
+ var iValue = y + 0.5;
+ for (var x = 0; x < max; x += 2) {
+ points[x] = (x >> 1) + 0.5;
+ points[x + 1] = iValue;
+ }
+ points = perspective_transform_1.transformPoints(transform, points);
+ // Quick check to see if points transformed to something inside the image;
+ // sufficient to check the endpoints
+ try {
+ var nudgedPoints = checkAndNudgePoints(image.width, image.height, points);
+ }
+ catch (e) {
+ return null;
+ }
+ // try {
+ for (var x = 0; x < max; x += 2) {
+ bits.set(x >> 1, y, image.get(Math.floor(nudgedPoints[x]), Math.floor(nudgedPoints[x + 1])));
+ }
+ }
+ return bits;
+ }
+ function createTransform(topLeft, topRight, bottomLeft, alignmentPattern, dimension) {
+ var dimMinusThree = dimension - 3.5;
+ var bottomRightX;
+ var bottomRightY;
+ var sourceBottomRightX;
+ var sourceBottomRightY;
+ if (alignmentPattern != null) {
+ bottomRightX = alignmentPattern.x;
+ bottomRightY = alignmentPattern.y;
+ sourceBottomRightX = sourceBottomRightY = dimMinusThree - 3;
+ }
+ else {
+ // Don't have an alignment pattern, just make up the bottom-right point
+ bottomRightX = (topRight.x - topLeft.x) + bottomLeft.x;
+ bottomRightY = (topRight.y - topLeft.y) + bottomLeft.y;
+ sourceBottomRightX = sourceBottomRightY = dimMinusThree;
+ }
+ return perspective_transform_1.quadrilateralToQuadrilateral(3.5, 3.5, dimMinusThree, 3.5, sourceBottomRightX, sourceBottomRightY, 3.5, dimMinusThree, topLeft.x, topLeft.y, topRight.x, topRight.y, bottomRightX, bottomRightY, bottomLeft.x, bottomLeft.y);
+ }
+ // Taken from 6th grade algebra
+ function distance(x1, y1, x2, y2) {
+ return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
+ }
+ // Attempts to locate an alignment pattern in a limited region of the image, which is guessed to contain it.
+ // overallEstModuleSize - estimated module size so far
+ // estAlignmentX - coordinate of center of area probably containing alignment pattern
+ // estAlignmentY - y coordinate of above
+ // allowanceFactor - number of pixels in all directions to search from the center
+ function findAlignmentInRegion(overallEstModuleSize, estAlignmentX, estAlignmentY, allowanceFactor, image) {
+ estAlignmentX = Math.floor(estAlignmentX);
+ estAlignmentY = Math.floor(estAlignmentY);
+ // Look for an alignment pattern (3 modules in size) around where it should be
+ var allowance = Math.floor(allowanceFactor * overallEstModuleSize);
+ var alignmentAreaLeftX = Math.max(0, estAlignmentX - allowance);
+ var alignmentAreaRightX = Math.min(image.width, estAlignmentX + allowance);
+ if (alignmentAreaRightX - alignmentAreaLeftX < overallEstModuleSize * 3) {
+ return null;
+ }
+ var alignmentAreaTopY = Math.max(0, estAlignmentY - allowance);
+ var alignmentAreaBottomY = Math.min(image.height - 1, estAlignmentY + allowance);
+ return alignment_finder_1.findAlignment(alignmentAreaLeftX, alignmentAreaTopY, alignmentAreaRightX - alignmentAreaLeftX, alignmentAreaBottomY - alignmentAreaTopY, overallEstModuleSize, image);
+ }
+ // Computes the dimension (number of modules on a size) of the QR Code based on the position of the finder
+ // patterns and estimated module size.
+ function computeDimension(topLeft, topRight, bottomLeft, moduleSize) {
+ var tltrCentersDimension = Math.round(distance(topLeft.x, topLeft.y, topRight.x, topRight.y) / moduleSize);
+ var tlblCentersDimension = Math.round(distance(topLeft.x, topLeft.y, bottomLeft.x, bottomLeft.y) / moduleSize);
+ var dimension = ((tltrCentersDimension + tlblCentersDimension) >> 1) + 7;
+ switch (dimension & 0x03) {
+ // mod 4
+ case 0:
+ dimension++;
+ break;
+ // 1? do nothing
+ case 2:
+ dimension--;
+ break;
+ }
+ return dimension;
+ }
+ // Deduces version information purely from QR Code dimensions.
+ // http://chan.catiewayne.com/z/src/131044167276.jpg
+ function getProvisionalVersionForDimension(dimension) {
+ if (dimension % 4 != 1) {
+ return null;
+ }
+ var versionNumber = (dimension - 17) >> 2;
+ if (versionNumber < 1 || versionNumber > 40) {
+ return null;
+ }
+ return version_1.getVersionForNumber(versionNumber);
+ }
+ // This method traces a line from a point in the image, in the direction towards another point.
+ // It begins in a black region, and keeps going until it finds white, then black, then white again.
+ // It reports the distance from the start to this point.
+ //
+ // This is used when figuring out how wide a finder pattern is, when the finder pattern
+ // may be skewed or rotated.
+ function sizeOfBlackWhiteBlackRun(fromX, fromY, toX, toY, image) {
+ fromX = Math.floor(fromX);
+ fromY = Math.floor(fromY);
+ toX = Math.floor(toX);
+ toY = Math.floor(toY);
+ // Mild variant of Bresenham's algorithm;
+ // see http://en.wikipedia.org/wiki/Bresenham's_line_algorithm
+ var steep = Math.abs(toY - fromY) > Math.abs(toX - fromX);
+ if (steep) {
+ var temp = fromX;
+ fromX = fromY;
+ fromY = temp;
+ temp = toX;
+ toX = toY;
+ toY = temp;
+ }
+ var dx = Math.abs(toX - fromX);
+ var dy = Math.abs(toY - fromY);
+ var error = -dx >> 1;
+ var xstep = fromX < toX ? 1 : -1;
+ var ystep = fromY < toY ? 1 : -1;
+ // In black pixels, looking for white, first or second time.
+ var state = 0;
+ // Loop up until x == toX, but not beyond
+ var xLimit = toX + xstep;
+ for (var x = fromX, y = fromY; x != xLimit; x += xstep) {
+ var realX = steep ? y : x;
+ var realY = steep ? x : y;
+ // Does current pixel mean we have moved white to black or vice versa?
+ // Scanning black in state 0,2 and white in state 1, so if we find the wrong
+ // color, advance to next state or end if we are in state 2 already
+ if ((state == 1) === image.get(realX, realY)) {
+ if (state == 2) {
+ return distance(x, y, fromX, fromY);
+ }
+ state++;
+ }
+ error += dy;
+ if (error > 0) {
+ if (y == toY) {
+ break;
+ }
+ y += ystep;
+ error -= dx;
+ }
+ }
+ // Found black-white-black; give the benefit of the doubt that the next pixel outside the image
+ // is "white" so this last point at (toX+xStep,toY) is the right ending. This is really a
+ // small approximation; (toX+xStep,toY+yStep) might be really correct. Ignore this.
+ if (state == 2) {
+ return distance(toX + xstep, toY, fromX, fromY);
+ }
+ // else we didn't find even black-white-black; no estimate is really possible
+ return NaN;
+ }
+ // Computes the total width of a finder pattern by looking for a black-white-black run from the center
+ // in the direction of another point (another finder pattern center), and in the opposite direction too.
+ function sizeOfBlackWhiteBlackRunBothWays(fromX, fromY, toX, toY, image) {
+ var result = sizeOfBlackWhiteBlackRun(fromX, fromY, toX, toY, image);
+ // Now count other way -- don't run off image though of course
+ var scale = 1;
+ var otherToX = fromX - (toX - fromX);
+ if (otherToX < 0) {
+ scale = fromX / (fromX - otherToX);
+ otherToX = 0;
+ }
+ else if (otherToX >= image.width) {
+ scale = (image.width - 1 - fromX) / (otherToX - fromX);
+ otherToX = image.width - 1;
+ }
+ var otherToY = (fromY - (toY - fromY) * scale);
+ scale = 1;
+ if (otherToY < 0) {
+ scale = fromY / (fromY - otherToY);
+ otherToY = 0;
+ }
+ else if (otherToY >= image.height) {
+ scale = (image.height - 1 - fromY) / (otherToY - fromY);
+ otherToY = image.height - 1;
+ }
+ otherToX = (fromX + (otherToX - fromX) * scale);
+ result += sizeOfBlackWhiteBlackRun(fromX, fromY, otherToX, otherToY, image);
+ return result - 1; // -1 because we counted the middle pixel twice
+ }
+ function calculateModuleSizeOneWay(pattern, otherPattern, image) {
+ var moduleSizeEst1 = sizeOfBlackWhiteBlackRunBothWays(pattern.x, pattern.y, otherPattern.x, otherPattern.y, image);
+ var moduleSizeEst2 = sizeOfBlackWhiteBlackRunBothWays(otherPattern.x, otherPattern.y, pattern.x, pattern.y, image);
+ if (helpers_1.isNaN(moduleSizeEst1)) {
+ return moduleSizeEst2 / 7;
+ }
+ if (helpers_1.isNaN(moduleSizeEst2)) {
+ return moduleSizeEst1 / 7;
+ }
+ // Average them, and divide by 7 since we've counted the width of 3 black modules,
+ // and 1 white and 1 black module on either side. Ergo, divide sum by 14.
+ return (moduleSizeEst1 + moduleSizeEst2) / 14;
+ }
+ // Computes an average estimated module size based on estimated derived from the positions of the three finder patterns.
+ function calculateModuleSize(topLeft, topRight, bottomLeft, image) {
+ return (calculateModuleSizeOneWay(topLeft, topRight, image) + calculateModuleSizeOneWay(topLeft, bottomLeft, image)) / 2;
+ }
+ function extract(image, location) {
+ var moduleSize = calculateModuleSize(location.topLeft, location.topRight, location.bottomLeft, image);
+ if (moduleSize < 1) {
+ return null;
+ }
+ var dimension = computeDimension(location.topLeft, location.topRight, location.bottomLeft, moduleSize);
+ if (!dimension) {
+ return null;
+ }
+ var provisionalVersion = getProvisionalVersionForDimension(dimension);
+ if (provisionalVersion == null) {
+ return null;
+ }
+ var modulesBetweenFPCenters = provisionalVersion.getDimensionForVersion() - 7;
+ var alignmentPattern = null;
+ // Anything above version 1 has an alignment pattern
+ if (provisionalVersion.alignmentPatternCenters.length > 0) {
+ // Guess where a "bottom right" finder pattern would have been
+ var bottomRightX = location.topRight.x - location.topLeft.x + location.bottomLeft.x;
+ var bottomRightY = location.topRight.y - location.topLeft.y + location.bottomLeft.y;
+ // Estimate that alignment pattern is closer by 3 modules
+ // from "bottom right" to known top left location
+ var correctionToTopLeft = 1 - 3 / modulesBetweenFPCenters;
+ var estAlignmentX = location.topLeft.x + correctionToTopLeft * (bottomRightX - location.topLeft.x);
+ var estAlignmentY = location.topLeft.y + correctionToTopLeft * (bottomRightY - location.topLeft.y);
+ // Kind of arbitrary -- expand search radius before giving up
+ for (var i = 4; i <= 16; i <<= 1) {
+ alignmentPattern = findAlignmentInRegion(moduleSize, estAlignmentX, estAlignmentY, i, image);
+ if (!alignmentPattern) {
+ continue;
+ }
+ break;
+ }
+ }
+ var transform = createTransform(location.topLeft, location.topRight, location.bottomLeft, alignmentPattern, dimension);
+ return bitArrayFromImage(image, dimension, transform);
+ }
+ exports.extract = extract;
+
+
+/***/ },
+/* 5 */
+/***/ function(module, exports, __webpack_require__) {
+
+ "use strict";
+ var helpers_1 = __webpack_require__(6);
+ function aboutEquals(center, moduleSize, i, j) {
+ if (Math.abs(i - center.y) <= moduleSize && Math.abs(j - center.x) <= moduleSize) {
+ var moduleSizeDiff = Math.abs(moduleSize - center.estimatedModuleSize);
+ return moduleSizeDiff <= 1 || moduleSizeDiff <= center.estimatedModuleSize;
+ }
+ return false;
+ }
+ function combineEstimate(center, i, j, newModuleSize) {
+ var combinedX = (center.x + j) / 2;
+ var combinedY = (center.y + i) / 2;
+ var combinedModuleSize = (center.estimatedModuleSize + newModuleSize) / 2;
+ return { x: combinedX, y: combinedY, estimatedModuleSize: combinedModuleSize };
+ }
+ // returns true if the proportions of the counts is close enough to the 1/1/1 ratios used by alignment
+ // patterns to be considered a match
+ function foundPatternCross(stateCount, moduleSize) {
+ var maxVariance = moduleSize / 2;
+ for (var i = 0; i < 3; i++) {
+ if (Math.abs(moduleSize - stateCount[i]) >= maxVariance) {
+ return false;
+ }
+ }
+ return true;
+ }
+ // Given a count of black/white/black pixels just seen and an end position,
+ // figures the location of the center of this black/white/black run.
+ function centerFromEnd(stateCount, end) {
+ var result = (end - stateCount[2]) - stateCount[1] / 2;
+ if (helpers_1.isNaN(result)) {
+ return null;
+ }
+ return result;
+ }
+ // After a horizontal scan finds a potential alignment pattern, this method
+ // "cross-checks" by scanning down vertically through the center of the possible
+ // alignment pattern to see if the same proportion is detected.
+ //
+ // startI - row where an alignment pattern was detected
+ // centerJ - center of the section that appears to cross an alignment pattern
+ // maxCount - maximum reasonable number of modules that should be observed in any reading state, based
+ // on the results of the horizontal scan
+ // originalStateCountTotal - The original state count total
+ function crossCheckVertical(startI, centerJ, maxCount, originalStateCountTotal, moduleSize, image) {
+ var maxI = image.height;
+ var stateCount = [0, 0, 0];
+ // Start counting up from center
+ var i = startI;
+ while (i >= 0 && image.get(centerJ, i) && stateCount[1] <= maxCount) {
+ stateCount[1]++;
+ i--;
+ }
+ // If already too many modules in this state or ran off the edge:
+ if (i < 0 || stateCount[1] > maxCount) {
+ return null;
+ }
+ while (i >= 0 && !image.get(centerJ, i) && stateCount[0] <= maxCount) {
+ stateCount[0]++;
+ i--;
+ }
+ if (stateCount[0] > maxCount) {
+ return null;
+ }
+ // Now also count down from center
+ i = startI + 1;
+ while (i < maxI && image.get(centerJ, i) && stateCount[1] <= maxCount) {
+ stateCount[1]++;
+ i++;
+ }
+ if (i == maxI || stateCount[1] > maxCount) {
+ return null;
+ }
+ while (i < maxI && !image.get(centerJ, i) && stateCount[2] <= maxCount) {
+ stateCount[2]++;
+ i++;
+ }
+ if (stateCount[2] > maxCount) {
+ return null;
+ }
+ var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2];
+ if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal) {
+ return null;
+ }
+ return foundPatternCross(stateCount, moduleSize) ? centerFromEnd(stateCount, i) : null;
+ }
+ function findAlignment(startX, startY, width, height, moduleSize, image) {
+ // Global State :(
+ var possibleCenters = [];
+ // This is called when a horizontal scan finds a possible alignment pattern. It will
+ // cross check with a vertical scan, and if successful, will see if this pattern had been
+ // found on a previous horizontal scan. If so, we consider it confirmed and conclude we have
+ // found the alignment pattern.
+ //
+ // stateCount - reading state module counts from horizontal scan
+ // i - where alignment pattern may be found
+ // j - end of possible alignment pattern in row
+ function handlePossibleCenter(stateCount, i, j, moduleSize) {
+ var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2];
+ var centerJ = centerFromEnd(stateCount, j);
+ if (centerJ == null) {
+ return null;
+ }
+ var centerI = crossCheckVertical(i, Math.floor(centerJ), 2 * stateCount[1], stateCountTotal, moduleSize, image);
+ if (centerI != null) {
+ var estimatedModuleSize = (stateCount[0] + stateCount[1] + stateCount[2]) / 3;
+ for (var i2 in possibleCenters) {
+ var center = possibleCenters[i2];
+ // Look for about the same center and module size:
+ if (aboutEquals(center, estimatedModuleSize, centerI, centerJ)) {
+ return combineEstimate(center, centerI, centerJ, estimatedModuleSize);
+ }
+ }
+ // Hadn't found this before; save it
+ var point = { x: centerJ, y: centerI, estimatedModuleSize: estimatedModuleSize };
+ possibleCenters.push(point);
+ }
+ return null;
+ }
+ var maxJ = startX + width;
+ var middleI = startY + (height >> 1);
+ // We are looking for black/white/black modules in 1:1:1 ratio;
+ // this tracks the number of black/white/black modules seen so far
+ var stateCount = [0, 0, 0]; // WTF
+ for (var iGen = 0; iGen < height; iGen++) {
+ // Search from middle outwards
+ var i = middleI + ((iGen & 0x01) == 0 ? ((iGen + 1) >> 1) : -((iGen + 1) >> 1));
+ stateCount[0] = 0;
+ stateCount[1] = 0;
+ stateCount[2] = 0;
+ var j = startX;
+ // Burn off leading white pixels before anything else; if we start in the middle of
+ // a white run, it doesn't make sense to count its length, since we don't know if the
+ // white run continued to the left of the start point
+ while (j < maxJ && !image.get(j, i)) {
+ j++;
+ }
+ var currentState = 0;
+ while (j < maxJ) {
+ if (image.get(j, i)) {
+ // Black pixel
+ if (currentState == 1) {
+ // Counting black pixels
+ stateCount[currentState]++;
+ }
+ else {
+ // Counting white pixels
+ if (currentState == 2) {
+ // A winner?
+ if (foundPatternCross(stateCount, moduleSize)) {
+ // Yes
+ confirmed = handlePossibleCenter(stateCount, i, j, moduleSize);
+ if (confirmed != null) {
+ return confirmed;
+ }
+ }
+ stateCount[0] = stateCount[2];
+ stateCount[1] = 1;
+ stateCount[2] = 0;
+ currentState = 1;
+ }
+ else {
+ stateCount[++currentState]++;
+ }
+ }
+ }
+ else {
+ // White pixel
+ if (currentState == 1) {
+ // Counting black pixels
+ currentState++;
+ }
+ stateCount[currentState]++;
+ }
+ j++;
+ }
+ if (foundPatternCross(stateCount, moduleSize)) {
+ var confirmed = handlePossibleCenter(stateCount, i, moduleSize, maxJ);
+ if (confirmed != null) {
+ return confirmed;
+ }
+ }
+ }
+ // Hmm, nothing we saw was observed and confirmed twice. If we had
+ // any guess at all, return it.
+ if (possibleCenters.length != 0) {
+ return possibleCenters[0];
+ }
+ return null;
+ }
+ exports.findAlignment = findAlignment;
+
+
+/***/ },
+/* 6 */
+/***/ function(module, exports) {
+
+ "use strict";
+ var BITS_SET_IN_HALF_BYTE = [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4];
+ function numBitsDiffering(a, b) {
+ a ^= b; // a now has a 1 bit exactly where its bit differs with b's
+ // Count bits set quickly with a series of lookups:
+ return BITS_SET_IN_HALF_BYTE[a & 0x0F] +
+ BITS_SET_IN_HALF_BYTE[((a >> 4) & 0x0F)] +
+ BITS_SET_IN_HALF_BYTE[((a >> 8) & 0x0F)] +
+ BITS_SET_IN_HALF_BYTE[((a >> 12) & 0x0F)] +
+ BITS_SET_IN_HALF_BYTE[((a >> 16) & 0x0F)] +
+ BITS_SET_IN_HALF_BYTE[((a >> 20) & 0x0F)] +
+ BITS_SET_IN_HALF_BYTE[((a >> 24) & 0x0F)] +
+ BITS_SET_IN_HALF_BYTE[((a >> 28) & 0x0F)];
+ }
+ exports.numBitsDiffering = numBitsDiffering;
+ // Taken from underscore JS
+ function isNaN(obj) {
+ return Object.prototype.toString.call(obj) === '[object Number]' && obj !== +obj;
+ }
+ exports.isNaN = isNaN;
+
+
+/***/ },
+/* 7 */
+/***/ function(module, exports) {
+
+ ///
+ "use strict";
+ function squareToQuadrilateral(x0, y0, x1, y1, x2, y2, x3, y3) {
+ var dx3 = x0 - x1 + x2 - x3;
+ var dy3 = y0 - y1 + y2 - y3;
+ if (dx3 == 0 && dy3 == 0) {
+ // Affine
+ return {
+ a11: x1 - x0,
+ a21: x2 - x1,
+ a31: x0,
+ a12: y1 - y0,
+ a22: y2 - y1,
+ a32: y0,
+ a13: 0,
+ a23: 0,
+ a33: 1
+ };
+ }
+ else {
+ var dx1 = x1 - x2;
+ var dx2 = x3 - x2;
+ var dy1 = y1 - y2;
+ var dy2 = y3 - y2;
+ var denominator = dx1 * dy2 - dx2 * dy1;
+ var a13 = (dx3 * dy2 - dx2 * dy3) / denominator;
+ var a23 = (dx1 * dy3 - dx3 * dy1) / denominator;
+ return {
+ a11: x1 - x0 + a13 * x1,
+ a21: x3 - x0 + a23 * x3,
+ a31: x0,
+ a12: y1 - y0 + a13 * y1,
+ a22: y3 - y0 + a23 * y3,
+ a32: y0,
+ a13: a13,
+ a23: a23,
+ a33: 1
+ };
+ }
+ }
+ function buildAdjoint(i) {
+ return {
+ a11: i.a22 * i.a33 - i.a23 * i.a32,
+ a21: i.a23 * i.a31 - i.a21 * i.a33,
+ a31: i.a21 * i.a32 - i.a22 * i.a31,
+ a12: i.a13 * i.a32 - i.a12 * i.a33,
+ a22: i.a11 * i.a33 - i.a13 * i.a31,
+ a32: i.a12 * i.a31 - i.a11 * i.a32,
+ a13: i.a12 * i.a23 - i.a13 * i.a22,
+ a23: i.a13 * i.a21 - i.a11 * i.a23,
+ a33: i.a11 * i.a22 - i.a12 * i.a21
+ };
+ }
+ function times(a, b) {
+ return {
+ a11: a.a11 * b.a11 + a.a21 * b.a12 + a.a31 * b.a13,
+ a21: a.a11 * b.a21 + a.a21 * b.a22 + a.a31 * b.a23,
+ a31: a.a11 * b.a31 + a.a21 * b.a32 + a.a31 * b.a33,
+ a12: a.a12 * b.a11 + a.a22 * b.a12 + a.a32 * b.a13,
+ a22: a.a12 * b.a21 + a.a22 * b.a22 + a.a32 * b.a23,
+ a32: a.a12 * b.a31 + a.a22 * b.a32 + a.a32 * b.a33,
+ a13: a.a13 * b.a11 + a.a23 * b.a12 + a.a33 * b.a13,
+ a23: a.a13 * b.a21 + a.a23 * b.a22 + a.a33 * b.a23,
+ a33: a.a13 * b.a31 + a.a23 * b.a32 + a.a33 * b.a33
+ };
+ }
+ function quadrilateralToSquare(x0, y0, x1, y1, x2, y2, x3, y3) {
+ // Here, the adjoint serves as the inverse:
+ return buildAdjoint(squareToQuadrilateral(x0, y0, x1, y1, x2, y2, x3, y3));
+ }
+ function transformPoints(transform, points) {
+ var max = points.length;
+ var a11 = transform.a11;
+ var a12 = transform.a12;
+ var a13 = transform.a13;
+ var a21 = transform.a21;
+ var a22 = transform.a22;
+ var a23 = transform.a23;
+ var a31 = transform.a31;
+ var a32 = transform.a32;
+ var a33 = transform.a33;
+ for (var i = 0; i < max; i += 2) {
+ var x = points[i];
+ var y = points[i + 1];
+ var denominator = a13 * x + a23 * y + a33;
+ points[i] = (a11 * x + a21 * y + a31) / denominator;
+ points[i + 1] = (a12 * x + a22 * y + a32) / denominator;
+ }
+ return points;
+ }
+ exports.transformPoints = transformPoints;
+ function quadrilateralToQuadrilateral(x0, y0, x1, y1, x2, y2, x3, y3, x0p, y0p, x1p, y1p, x2p, y2p, x3p, y3p) {
+ var qToS = quadrilateralToSquare(x0, y0, x1, y1, x2, y2, x3, y3);
+ var sToQ = squareToQuadrilateral(x0p, y0p, x1p, y1p, x2p, y2p, x3p, y3p);
+ return times(sToQ, qToS);
+ }
+ exports.quadrilateralToQuadrilateral = quadrilateralToQuadrilateral;
+
+
+/***/ },
+/* 8 */
+/***/ function(module, exports, __webpack_require__) {
+
+ "use strict";
+ var helpers_1 = __webpack_require__(6);
+ var VERSION_DECODE_INFO = [
+ 0x07C94, 0x085BC, 0x09A99, 0x0A4D3, 0x0BBF6,
+ 0x0C762, 0x0D847, 0x0E60D, 0x0F928, 0x10B78,
+ 0x1145D, 0x12A17, 0x13532, 0x149A6, 0x15683,
+ 0x168C9, 0x177EC, 0x18EC4, 0x191E1, 0x1AFAB,
+ 0x1B08E, 0x1CC1A, 0x1D33F, 0x1ED75, 0x1F250,
+ 0x209D5, 0x216F0, 0x228BA, 0x2379F, 0x24B0B,
+ 0x2542E, 0x26A64, 0x27541, 0x28C69,
+ ];
+ var ECB = (function () {
+ function ECB(_count, _dataCodewords) {
+ this.count = _count;
+ this.dataCodewords = _dataCodewords;
+ }
+ return ECB;
+ }());
+ var ECBlocks = (function () {
+ function ECBlocks(_ecCodewordsPerBlock) {
+ var _ecBlocks = [];
+ for (var _i = 1; _i < arguments.length; _i++) {
+ _ecBlocks[_i - 1] = arguments[_i];
+ }
+ this.ecCodewordsPerBlock = _ecCodewordsPerBlock;
+ this.ecBlocks = _ecBlocks;
+ }
+ ECBlocks.prototype.getNumBlocks = function () {
+ return this.ecBlocks.reduce(function (a, b) { return (a + b.count); }, 0);
+ };
+ ECBlocks.prototype.getTotalECCodewords = function () {
+ return this.ecCodewordsPerBlock * this.getNumBlocks();
+ };
+ return ECBlocks;
+ }());
+ var Version = (function () {
+ function Version(_versionNumber, _alignmentPatternCenters) {
+ var _ecBlocks = [];
+ for (var _i = 2; _i < arguments.length; _i++) {
+ _ecBlocks[_i - 2] = arguments[_i];
+ }
+ this.versionNumber = _versionNumber;
+ this.alignmentPatternCenters = _alignmentPatternCenters;
+ this.ecBlocks = _ecBlocks;
+ var total = 0;
+ var ecCodewords = this.ecBlocks[0].ecCodewordsPerBlock;
+ var ecbArray = this.ecBlocks[0].ecBlocks;
+ ecbArray.forEach(function (ecBlock) {
+ total += ecBlock.count * (ecBlock.dataCodewords + ecCodewords);
+ });
+ this.totalCodewords = total;
+ }
+ Version.prototype.getDimensionForVersion = function () {
+ return 17 + 4 * this.versionNumber;
+ };
+ Version.prototype.getECBlocksForLevel = function (ecLevel) {
+ return this.ecBlocks[ecLevel.ordinal];
+ };
+ Version.decodeVersionInformation = function (versionBits) {
+ var bestDifference = Infinity;
+ var bestVersion = 0;
+ for (var i = 0; i < VERSION_DECODE_INFO.length; i++) {
+ var targetVersion = VERSION_DECODE_INFO[i];
+ // Do the version info bits match exactly? done.
+ if (targetVersion == versionBits) {
+ return getVersionForNumber(i + 7);
+ }
+ // Otherwise see if this is the closest to a real version info bit string
+ // we have seen so far
+ var bitsDifference = helpers_1.numBitsDiffering(versionBits, targetVersion);
+ if (bitsDifference < bestDifference) {
+ bestVersion = i + 7;
+ bestDifference = bitsDifference;
+ }
+ }
+ // We can tolerate up to 3 bits of error since no two version info codewords will
+ // differ in less than 8 bits.
+ if (bestDifference <= 3) {
+ return getVersionForNumber(bestVersion);
+ }
+ // If we didn't find a close enough match, fail
+ return null;
+ };
+ return Version;
+ }());
+ exports.Version = Version;
+ var VERSIONS = [
+ new Version(1, [], new ECBlocks(7, new ECB(1, 19)), new ECBlocks(10, new ECB(1, 16)), new ECBlocks(13, new ECB(1, 13)), new ECBlocks(17, new ECB(1, 9))),
+ new Version(2, [6, 18], new ECBlocks(10, new ECB(1, 34)), new ECBlocks(16, new ECB(1, 28)), new ECBlocks(22, new ECB(1, 22)), new ECBlocks(28, new ECB(1, 16))),
+ new Version(3, [6, 22], new ECBlocks(15, new ECB(1, 55)), new ECBlocks(26, new ECB(1, 44)), new ECBlocks(18, new ECB(2, 17)), new ECBlocks(22, new ECB(2, 13))),
+ new Version(4, [6, 26], new ECBlocks(20, new ECB(1, 80)), new ECBlocks(18, new ECB(2, 32)), new ECBlocks(26, new ECB(2, 24)), new ECBlocks(16, new ECB(4, 9))),
+ new Version(5, [6, 30], new ECBlocks(26, new ECB(1, 108)), new ECBlocks(24, new ECB(2, 43)), new ECBlocks(18, new ECB(2, 15), new ECB(2, 16)), new ECBlocks(22, new ECB(2, 11), new ECB(2, 12))),
+ new Version(6, [6, 34], new ECBlocks(18, new ECB(2, 68)), new ECBlocks(16, new ECB(4, 27)), new ECBlocks(24, new ECB(4, 19)), new ECBlocks(28, new ECB(4, 15))),
+ new Version(7, [6, 22, 38], new ECBlocks(20, new ECB(2, 78)), new ECBlocks(18, new ECB(4, 31)), new ECBlocks(18, new ECB(2, 14), new ECB(4, 15)), new ECBlocks(26, new ECB(4, 13), new ECB(1, 14))),
+ new Version(8, [6, 24, 42], new ECBlocks(24, new ECB(2, 97)), new ECBlocks(22, new ECB(2, 38), new ECB(2, 39)), new ECBlocks(22, new ECB(4, 18), new ECB(2, 19)), new ECBlocks(26, new ECB(4, 14), new ECB(2, 15))),
+ new Version(9, [6, 26, 46], new ECBlocks(30, new ECB(2, 116)), new ECBlocks(22, new ECB(3, 36), new ECB(2, 37)), new ECBlocks(20, new ECB(4, 16), new ECB(4, 17)), new ECBlocks(24, new ECB(4, 12), new ECB(4, 13))),
+ new Version(10, [6, 28, 50], new ECBlocks(18, new ECB(2, 68), new ECB(2, 69)), new ECBlocks(26, new ECB(4, 43), new ECB(1, 44)), new ECBlocks(24, new ECB(6, 19), new ECB(2, 20)), new ECBlocks(28, new ECB(6, 15), new ECB(2, 16))),
+ new Version(11, [6, 30, 54], new ECBlocks(20, new ECB(4, 81)), new ECBlocks(30, new ECB(1, 50), new ECB(4, 51)), new ECBlocks(28, new ECB(4, 22), new ECB(4, 23)), new ECBlocks(24, new ECB(3, 12), new ECB(8, 13))),
+ new Version(12, [6, 32, 58], new ECBlocks(24, new ECB(2, 92), new ECB(2, 93)), new ECBlocks(22, new ECB(6, 36), new ECB(2, 37)), new ECBlocks(26, new ECB(4, 20), new ECB(6, 21)), new ECBlocks(28, new ECB(7, 14), new ECB(4, 15))),
+ new Version(13, [6, 34, 62], new ECBlocks(26, new ECB(4, 107)), new ECBlocks(22, new ECB(8, 37), new ECB(1, 38)), new ECBlocks(24, new ECB(8, 20), new ECB(4, 21)), new ECBlocks(22, new ECB(12, 11), new ECB(4, 12))),
+ new Version(14, [6, 26, 46, 66], new ECBlocks(30, new ECB(3, 115), new ECB(1, 116)), new ECBlocks(24, new ECB(4, 40), new ECB(5, 41)), new ECBlocks(20, new ECB(11, 16), new ECB(5, 17)), new ECBlocks(24, new ECB(11, 12), new ECB(5, 13))),
+ new Version(15, [6, 26, 48, 70], new ECBlocks(22, new ECB(5, 87), new ECB(1, 88)), new ECBlocks(24, new ECB(5, 41), new ECB(5, 42)), new ECBlocks(30, new ECB(5, 24), new ECB(7, 25)), new ECBlocks(24, new ECB(11, 12), new ECB(7, 13))),
+ new Version(16, [6, 26, 50, 74], new ECBlocks(24, new ECB(5, 98), new ECB(1, 99)), new ECBlocks(28, new ECB(7, 45), new ECB(3, 46)), new ECBlocks(24, new ECB(15, 19), new ECB(2, 20)), new ECBlocks(30, new ECB(3, 15), new ECB(13, 16))),
+ new Version(17, [6, 30, 54, 78], new ECBlocks(28, new ECB(1, 107), new ECB(5, 108)), new ECBlocks(28, new ECB(10, 46), new ECB(1, 47)), new ECBlocks(28, new ECB(1, 22), new ECB(15, 23)), new ECBlocks(28, new ECB(2, 14), new ECB(17, 15))),
+ new Version(18, [6, 30, 56, 82], new ECBlocks(30, new ECB(5, 120), new ECB(1, 121)), new ECBlocks(26, new ECB(9, 43), new ECB(4, 44)), new ECBlocks(28, new ECB(17, 22), new ECB(1, 23)), new ECBlocks(28, new ECB(2, 14), new ECB(19, 15))),
+ new Version(19, [6, 30, 58, 86], new ECBlocks(28, new ECB(3, 113), new ECB(4, 114)), new ECBlocks(26, new ECB(3, 44), new ECB(11, 45)), new ECBlocks(26, new ECB(17, 21), new ECB(4, 22)), new ECBlocks(26, new ECB(9, 13), new ECB(16, 14))),
+ new Version(20, [6, 34, 62, 90], new ECBlocks(28, new ECB(3, 107), new ECB(5, 108)), new ECBlocks(26, new ECB(3, 41), new ECB(13, 42)), new ECBlocks(30, new ECB(15, 24), new ECB(5, 25)), new ECBlocks(28, new ECB(15, 15), new ECB(10, 16))),
+ new Version(21, [6, 28, 50, 72, 94], new ECBlocks(28, new ECB(4, 116), new ECB(4, 117)), new ECBlocks(26, new ECB(17, 42)), new ECBlocks(28, new ECB(17, 22), new ECB(6, 23)), new ECBlocks(30, new ECB(19, 16), new ECB(6, 17))),
+ new Version(22, [6, 26, 50, 74, 98], new ECBlocks(28, new ECB(2, 111), new ECB(7, 112)), new ECBlocks(28, new ECB(17, 46)), new ECBlocks(30, new ECB(7, 24), new ECB(16, 25)), new ECBlocks(24, new ECB(34, 13))),
+ new Version(23, [6, 30, 54, 74, 102], new ECBlocks(30, new ECB(4, 121), new ECB(5, 122)), new ECBlocks(28, new ECB(4, 47), new ECB(14, 48)), new ECBlocks(30, new ECB(11, 24), new ECB(14, 25)), new ECBlocks(30, new ECB(16, 15), new ECB(14, 16))),
+ new Version(24, [6, 28, 54, 80, 106], new ECBlocks(30, new ECB(6, 117), new ECB(4, 118)), new ECBlocks(28, new ECB(6, 45), new ECB(14, 46)), new ECBlocks(30, new ECB(11, 24), new ECB(16, 25)), new ECBlocks(30, new ECB(30, 16), new ECB(2, 17))),
+ new Version(25, [6, 32, 58, 84, 110], new ECBlocks(26, new ECB(8, 106), new ECB(4, 107)), new ECBlocks(28, new ECB(8, 47), new ECB(13, 48)), new ECBlocks(30, new ECB(7, 24), new ECB(22, 25)), new ECBlocks(30, new ECB(22, 15), new ECB(13, 16))),
+ new Version(26, [6, 30, 58, 86, 114], new ECBlocks(28, new ECB(10, 114), new ECB(2, 115)), new ECBlocks(28, new ECB(19, 46), new ECB(4, 47)), new ECBlocks(28, new ECB(28, 22), new ECB(6, 23)), new ECBlocks(30, new ECB(33, 16), new ECB(4, 17))),
+ new Version(27, [6, 34, 62, 90, 118], new ECBlocks(30, new ECB(8, 122), new ECB(4, 123)), new ECBlocks(28, new ECB(22, 45), new ECB(3, 46)), new ECBlocks(30, new ECB(8, 23), new ECB(26, 24)), new ECBlocks(30, new ECB(12, 15), new ECB(28, 16))),
+ new Version(28, [6, 26, 50, 74, 98, 122], new ECBlocks(30, new ECB(3, 117), new ECB(10, 118)), new ECBlocks(28, new ECB(3, 45), new ECB(23, 46)), new ECBlocks(30, new ECB(4, 24), new ECB(31, 25)), new ECBlocks(30, new ECB(11, 15), new ECB(31, 16))),
+ new Version(29, [6, 30, 54, 78, 102, 126], new ECBlocks(30, new ECB(7, 116), new ECB(7, 117)), new ECBlocks(28, new ECB(21, 45), new ECB(7, 46)), new ECBlocks(30, new ECB(1, 23), new ECB(37, 24)), new ECBlocks(30, new ECB(19, 15), new ECB(26, 16))),
+ new Version(30, [6, 26, 52, 78, 104, 130], new ECBlocks(30, new ECB(5, 115), new ECB(10, 116)), new ECBlocks(28, new ECB(19, 47), new ECB(10, 48)), new ECBlocks(30, new ECB(15, 24), new ECB(25, 25)), new ECBlocks(30, new ECB(23, 15), new ECB(25, 16))),
+ new Version(31, [6, 30, 56, 82, 108, 134], new ECBlocks(30, new ECB(13, 115), new ECB(3, 116)), new ECBlocks(28, new ECB(2, 46), new ECB(29, 47)), new ECBlocks(30, new ECB(42, 24), new ECB(1, 25)), new ECBlocks(30, new ECB(23, 15), new ECB(28, 16))),
+ new Version(32, [6, 34, 60, 86, 112, 138], new ECBlocks(30, new ECB(17, 115)), new ECBlocks(28, new ECB(10, 46), new ECB(23, 47)), new ECBlocks(30, new ECB(10, 24), new ECB(35, 25)), new ECBlocks(30, new ECB(19, 15), new ECB(35, 16))),
+ new Version(33, [6, 30, 58, 86, 114, 142], new ECBlocks(30, new ECB(17, 115), new ECB(1, 116)), new ECBlocks(28, new ECB(14, 46), new ECB(21, 47)), new ECBlocks(30, new ECB(29, 24), new ECB(19, 25)), new ECBlocks(30, new ECB(11, 15), new ECB(46, 16))),
+ new Version(34, [6, 34, 62, 90, 118, 146], new ECBlocks(30, new ECB(13, 115), new ECB(6, 116)), new ECBlocks(28, new ECB(14, 46), new ECB(23, 47)), new ECBlocks(30, new ECB(44, 24), new ECB(7, 25)), new ECBlocks(30, new ECB(59, 16), new ECB(1, 17))),
+ new Version(35, [6, 30, 54, 78, 102, 126, 150], new ECBlocks(30, new ECB(12, 121), new ECB(7, 122)), new ECBlocks(28, new ECB(12, 47), new ECB(26, 48)), new ECBlocks(30, new ECB(39, 24), new ECB(14, 25)), new ECBlocks(30, new ECB(22, 15), new ECB(41, 16))),
+ new Version(36, [6, 24, 50, 76, 102, 128, 154], new ECBlocks(30, new ECB(6, 121), new ECB(14, 122)), new ECBlocks(28, new ECB(6, 47), new ECB(34, 48)), new ECBlocks(30, new ECB(46, 24), new ECB(10, 25)), new ECBlocks(30, new ECB(2, 15), new ECB(64, 16))),
+ new Version(37, [6, 28, 54, 80, 106, 132, 158], new ECBlocks(30, new ECB(17, 122), new ECB(4, 123)), new ECBlocks(28, new ECB(29, 46), new ECB(14, 47)), new ECBlocks(30, new ECB(49, 24), new ECB(10, 25)), new ECBlocks(30, new ECB(24, 15), new ECB(46, 16))),
+ new Version(38, [6, 32, 58, 84, 110, 136, 162], new ECBlocks(30, new ECB(4, 122), new ECB(18, 123)), new ECBlocks(28, new ECB(13, 46), new ECB(32, 47)), new ECBlocks(30, new ECB(48, 24), new ECB(14, 25)), new ECBlocks(30, new ECB(42, 15), new ECB(32, 16))),
+ new Version(39, [6, 26, 54, 82, 110, 138, 166], new ECBlocks(30, new ECB(20, 117), new ECB(4, 118)), new ECBlocks(28, new ECB(40, 47), new ECB(7, 48)), new ECBlocks(30, new ECB(43, 24), new ECB(22, 25)), new ECBlocks(30, new ECB(10, 15), new ECB(67, 16))),
+ new Version(40, [6, 30, 58, 86, 114, 142, 170], new ECBlocks(30, new ECB(19, 118), new ECB(6, 119)), new ECBlocks(28, new ECB(18, 47), new ECB(31, 48)), new ECBlocks(30, new ECB(34, 24), new ECB(34, 25)), new ECBlocks(30, new ECB(20, 15), new ECB(61, 16))),
+ ];
+ function getVersionForNumber(versionNumber) {
+ if (versionNumber < 1 || versionNumber > 40) {
+ throw new Error("Invalid version number " + versionNumber);
+ }
+ return VERSIONS[versionNumber - 1];
+ }
+ exports.getVersionForNumber = getVersionForNumber;
+
+
+/***/ },
+/* 9 */
+/***/ function(module, exports, __webpack_require__) {
+
+ "use strict";
+ var bitmatrix_1 = __webpack_require__(2);
+ var decodeqrdata_1 = __webpack_require__(10);
+ var helpers_1 = __webpack_require__(6);
+ var reedsolomon_1 = __webpack_require__(12);
+ var version_1 = __webpack_require__(8);
+ var FORMAT_INFO_MASK_QR = 0x5412;
+ var FORMAT_INFO_DECODE_LOOKUP = [
+ [0x5412, 0x00],
+ [0x5125, 0x01],
+ [0x5E7C, 0x02],
+ [0x5B4B, 0x03],
+ [0x45F9, 0x04],
+ [0x40CE, 0x05],
+ [0x4F97, 0x06],
+ [0x4AA0, 0x07],
+ [0x77C4, 0x08],
+ [0x72F3, 0x09],
+ [0x7DAA, 0x0A],
+ [0x789D, 0x0B],
+ [0x662F, 0x0C],
+ [0x6318, 0x0D],
+ [0x6C41, 0x0E],
+ [0x6976, 0x0F],
+ [0x1689, 0x10],
+ [0x13BE, 0x11],
+ [0x1CE7, 0x12],
+ [0x19D0, 0x13],
+ [0x0762, 0x14],
+ [0x0255, 0x15],
+ [0x0D0C, 0x16],
+ [0x083B, 0x17],
+ [0x355F, 0x18],
+ [0x3068, 0x19],
+ [0x3F31, 0x1A],
+ [0x3A06, 0x1B],
+ [0x24B4, 0x1C],
+ [0x2183, 0x1D],
+ [0x2EDA, 0x1E],
+ [0x2BED, 0x1F],
+ ];
+ var DATA_MASKS = [
+ function (i, j) { return ((i + j) & 0x01) === 0; },
+ function (i, j) { return (i & 0x01) === 0; },
+ function (i, j) { return j % 3 == 0; },
+ function (i, j) { return (i + j) % 3 === 0; },
+ function (i, j) { return (((i >> 1) + (j / 3)) & 0x01) === 0; },
+ function (i, j) { return ((i * j) & 0x01) + ((i * j) % 3) === 0; },
+ function (i, j) { return ((((i * j) & 0x01) + ((i * j) % 3)) & 0x01) === 0; },
+ function (i, j) { return ((((i + j) & 0x01) + ((i * j) % 3)) & 0x01) === 0; },
+ ];
+ var ERROR_CORRECTION_LEVELS = [
+ { ordinal: 1, bits: 0x00, name: "M" },
+ { ordinal: 0, bits: 0x01, name: "L" },
+ { ordinal: 3, bits: 0x02, name: "H" },
+ { ordinal: 2, bits: 0x03, name: "Q" },
+ ];
+ function buildFunctionPattern(version) {
+ var dimension = version.getDimensionForVersion();
+ var emptyArray = new Array(dimension * dimension);
+ for (var i = 0; i < emptyArray.length; i++) {
+ emptyArray[i] = false;
+ }
+ var bitMatrix = new bitmatrix_1.BitMatrix(emptyArray, dimension);
+ ///BitMatrix bitMatrix = new BitMatrix(dimension);
+ // Top left finder pattern + separator + format
+ bitMatrix.setRegion(0, 0, 9, 9);
+ // Top right finder pattern + separator + format
+ bitMatrix.setRegion(dimension - 8, 0, 8, 9);
+ // Bottom left finder pattern + separator + format
+ bitMatrix.setRegion(0, dimension - 8, 9, 8);
+ // Alignment patterns
+ var max = version.alignmentPatternCenters.length;
+ for (var x = 0; x < max; x++) {
+ var i = version.alignmentPatternCenters[x] - 2;
+ for (var y = 0; y < max; y++) {
+ if ((x == 0 && (y == 0 || y == max - 1)) || (x == max - 1 && y == 0)) {
+ // No alignment patterns near the three finder paterns
+ continue;
+ }
+ bitMatrix.setRegion(version.alignmentPatternCenters[y] - 2, i, 5, 5);
+ }
+ }
+ // Vertical timing pattern
+ bitMatrix.setRegion(6, 9, 1, dimension - 17);
+ // Horizontal timing pattern
+ bitMatrix.setRegion(9, 6, dimension - 17, 1);
+ if (version.versionNumber > 6) {
+ // Version info, top right
+ bitMatrix.setRegion(dimension - 11, 0, 3, 6);
+ // Version info, bottom left
+ bitMatrix.setRegion(0, dimension - 11, 6, 3);
+ }
+ return bitMatrix;
+ }
+ function readCodewords(matrix, version, formatInfo) {
+ // Get the data mask for the format used in this QR Code. This will exclude
+ // some bits from reading as we wind through the bit matrix.
+ var dataMask = DATA_MASKS[formatInfo.dataMask];
+ var dimension = matrix.height;
+ var funcPattern = buildFunctionPattern(version);
+ var readingUp = true;
+ var result = [];
+ var resultOffset = 0;
+ var currentByte = 0;
+ var bitsRead = 0;
+ // Read columns in pairs, from right to left
+ for (var j = dimension - 1; j > 0; j -= 2) {
+ if (j == 6) {
+ // Skip whole column with vertical alignment pattern;
+ // saves time and makes the other code proceed more cleanly
+ j--;
+ }
+ // Read alternatingly from bottom to top then top to bottom
+ for (var count = 0; count < dimension; count++) {
+ var i = readingUp ? dimension - 1 - count : count;
+ for (var col = 0; col < 2; col++) {
+ // Ignore bits covered by the function pattern
+ if (!funcPattern.get(j - col, i)) {
+ // Read a bit
+ bitsRead++;
+ currentByte <<= 1;
+ if (matrix.get(j - col, i) !== dataMask(i, j - col)) {
+ currentByte |= 1;
+ }
+ // If we've made a whole byte, save it off
+ if (bitsRead == 8) {
+ result[resultOffset++] = currentByte & 0xFF;
+ bitsRead = 0;
+ currentByte = 0;
+ }
+ }
+ }
+ }
+ readingUp = !readingUp; // switch directions
+ }
+ if (resultOffset != version.totalCodewords) {
+ return null;
+ }
+ return result;
+ }
+ function readVersion(matrix) {
+ var dimension = matrix.height;
+ var provisionalVersion = (dimension - 17) >> 2;
+ if (provisionalVersion <= 6) {
+ return version_1.getVersionForNumber(provisionalVersion);
+ }
+ // Read top-right version info: 3 wide by 6 tall
+ var versionBits = 0;
+ var ijMin = dimension - 11;
+ for (var j = 5; j >= 0; j--) {
+ for (var i = dimension - 9; i >= ijMin; i--) {
+ versionBits = matrix.copyBit(i, j, versionBits);
+ }
+ }
+ var parsedVersion = version_1.Version.decodeVersionInformation(versionBits);
+ if (parsedVersion != null && parsedVersion.getDimensionForVersion() == dimension) {
+ return parsedVersion;
+ }
+ // Hmm, failed. Try bottom left: 6 wide by 3 tall
+ versionBits = 0;
+ for (var i = 5; i >= 0; i--) {
+ for (var j = dimension - 9; j >= ijMin; j--) {
+ versionBits = matrix.copyBit(i, j, versionBits);
+ }
+ }
+ parsedVersion = version_1.Version.decodeVersionInformation(versionBits);
+ if (parsedVersion != null && parsedVersion.getDimensionForVersion() == dimension) {
+ return parsedVersion;
+ }
+ return null;
+ }
+ function newFormatInformation(formatInfo) {
+ return {
+ errorCorrectionLevel: ERROR_CORRECTION_LEVELS[(formatInfo >> 3) & 0x03],
+ dataMask: formatInfo & 0x07
+ };
+ }
+ function doDecodeFormatInformation(maskedFormatInfo1, maskedFormatInfo2) {
+ // Find the int in FORMAT_INFO_DECODE_LOOKUP with fewest bits differing
+ var bestDifference = Infinity;
+ var bestFormatInfo = 0;
+ for (var i = 0; i < FORMAT_INFO_DECODE_LOOKUP.length; i++) {
+ var decodeInfo = FORMAT_INFO_DECODE_LOOKUP[i];
+ var targetInfo = decodeInfo[0];
+ if (targetInfo == maskedFormatInfo1 || targetInfo == maskedFormatInfo2) {
+ // Found an exact match
+ return newFormatInformation(decodeInfo[1]);
+ }
+ var bitsDifference = helpers_1.numBitsDiffering(maskedFormatInfo1, targetInfo);
+ if (bitsDifference < bestDifference) {
+ bestFormatInfo = decodeInfo[1];
+ bestDifference = bitsDifference;
+ }
+ if (maskedFormatInfo1 != maskedFormatInfo2) {
+ // also try the other option
+ bitsDifference = helpers_1.numBitsDiffering(maskedFormatInfo2, targetInfo);
+ if (bitsDifference < bestDifference) {
+ bestFormatInfo = decodeInfo[1];
+ bestDifference = bitsDifference;
+ }
+ }
+ }
+ // Hamming distance of the 32 masked codes is 7, by construction, so <= 3 bits
+ // differing means we found a match
+ if (bestDifference <= 3)
+ return newFormatInformation(bestFormatInfo);
+ return null;
+ }
+ function decodeFormatInformation(maskedFormatInfo1, maskedFormatInfo2) {
+ var formatInfo = doDecodeFormatInformation(maskedFormatInfo1, maskedFormatInfo2);
+ if (formatInfo) {
+ return formatInfo;
+ }
+ // Should return null, but, some QR codes apparently
+ // do not mask this info. Try again by actually masking the pattern
+ // first
+ return doDecodeFormatInformation(maskedFormatInfo1 ^ FORMAT_INFO_MASK_QR, maskedFormatInfo2 ^ FORMAT_INFO_MASK_QR);
+ }
+ function readFormatInformation(matrix) {
+ // Read top-left format info bits
+ var formatInfoBits1 = 0;
+ for (var i = 0; i < 6; i++) {
+ formatInfoBits1 = matrix.copyBit(i, 8, formatInfoBits1);
+ }
+ // .. and skip a bit in the timing pattern ...
+ formatInfoBits1 = matrix.copyBit(7, 8, formatInfoBits1);
+ formatInfoBits1 = matrix.copyBit(8, 8, formatInfoBits1);
+ formatInfoBits1 = matrix.copyBit(8, 7, formatInfoBits1);
+ // .. and skip a bit in the timing pattern ...
+ for (var j = 5; j >= 0; j--) {
+ formatInfoBits1 = matrix.copyBit(8, j, formatInfoBits1);
+ }
+ // Read the top-right/bottom-left pattern too
+ var dimension = matrix.height;
+ var formatInfoBits2 = 0;
+ var jMin = dimension - 7;
+ for (var j = dimension - 1; j >= jMin; j--) {
+ formatInfoBits2 = matrix.copyBit(8, j, formatInfoBits2);
+ }
+ for (var i = dimension - 8; i < dimension; i++) {
+ formatInfoBits2 = matrix.copyBit(i, 8, formatInfoBits2);
+ }
+ // parsedFormatInfo = FormatInformation.decodeFormatInformation(formatInfoBits1, formatInfoBits2);
+ var parsedFormatInfo = decodeFormatInformation(formatInfoBits1, formatInfoBits2);
+ if (parsedFormatInfo != null) {
+ return parsedFormatInfo;
+ }
+ return null;
+ }
+ function getDataBlocks(rawCodewords, version, ecLevel) {
+ if (rawCodewords.length != version.totalCodewords) {
+ throw new Error("Invalid number of codewords for version; got " + rawCodewords.length + " expected " + version.totalCodewords);
+ }
+ // Figure out the number and size of data blocks used by this version and
+ // error correction level
+ var ecBlocks = version.getECBlocksForLevel(ecLevel);
+ // First count the total number of data blocks
+ var totalBlocks = 0;
+ var ecBlockArray = ecBlocks.ecBlocks;
+ ecBlockArray.forEach(function (ecBlock) {
+ totalBlocks += ecBlock.count;
+ });
+ // Now establish DataBlocks of the appropriate size and number of data codewords
+ var result = new Array(totalBlocks);
+ var numResultBlocks = 0;
+ ecBlockArray.forEach(function (ecBlock) {
+ for (var i = 0; i < ecBlock.count; i++) {
+ var numDataCodewords = ecBlock.dataCodewords;
+ var numBlockCodewords = ecBlocks.ecCodewordsPerBlock + numDataCodewords;
+ result[numResultBlocks++] = { numDataCodewords: numDataCodewords, codewords: new Array(numBlockCodewords) };
+ }
+ });
+ // All blocks have the same amount of data, except that the last n
+ // (where n may be 0) have 1 more byte. Figure out where these start.
+ var shorterBlocksTotalCodewords = result[0].codewords.length;
+ var longerBlocksStartAt = result.length - 1;
+ while (longerBlocksStartAt >= 0) {
+ var numCodewords = result[longerBlocksStartAt].codewords.length;
+ if (numCodewords == shorterBlocksTotalCodewords) {
+ break;
+ }
+ longerBlocksStartAt--;
+ }
+ longerBlocksStartAt++;
+ var shorterBlocksNumDataCodewords = shorterBlocksTotalCodewords - ecBlocks.ecCodewordsPerBlock;
+ // The last elements of result may be 1 element longer;
+ // first fill out as many elements as all of them have
+ var rawCodewordsOffset = 0;
+ for (var i = 0; i < shorterBlocksNumDataCodewords; i++) {
+ for (var j = 0; j < numResultBlocks; j++) {
+ result[j].codewords[i] = rawCodewords[rawCodewordsOffset++];
+ }
+ }
+ // Fill out the last data block in the longer ones
+ for (var j = longerBlocksStartAt; j < numResultBlocks; j++) {
+ result[j].codewords[shorterBlocksNumDataCodewords] = rawCodewords[rawCodewordsOffset++];
+ }
+ // Now add in error correction blocks
+ var max = result[0].codewords.length;
+ for (var i = shorterBlocksNumDataCodewords; i < max; i++) {
+ for (var j = 0; j < numResultBlocks; j++) {
+ var iOffset = j < longerBlocksStartAt ? i : i + 1;
+ result[j].codewords[iOffset] = rawCodewords[rawCodewordsOffset++];
+ }
+ }
+ return result;
+ }
+ function correctErrors(codewordBytes, numDataCodewords) {
+ var rsDecoder = new reedsolomon_1.ReedSolomonDecoder();
+ var numCodewords = codewordBytes.length;
+ // First read into an array of ints
+ var codewordsInts = new Array(numCodewords);
+ for (var i = 0; i < numCodewords; i++) {
+ codewordsInts[i] = codewordBytes[i] & 0xFF;
+ }
+ var numECCodewords = codewordBytes.length - numDataCodewords;
+ if (!rsDecoder.decode(codewordsInts, numECCodewords))
+ return false;
+ // Copy back into array of bytes -- only need to worry about the bytes that were data
+ // We don't care about errors in the error-correction codewords
+ for (var i = 0; i < numDataCodewords; i++) {
+ codewordBytes[i] = codewordsInts[i];
+ }
+ return true;
+ }
+ function decodeMatrix(matrix) {
+ var version = readVersion(matrix);
+ if (!version) {
+ return null;
+ }
+ var formatInfo = readFormatInformation(matrix);
+ if (!formatInfo) {
+ return null;
+ }
+ var ecLevel = formatInfo.errorCorrectionLevel;
+ // Read codewords
+ var codewords = readCodewords(matrix, version, formatInfo);
+ if (!codewords) {
+ return null;
+ }
+ // Separate into data blocks
+ var dataBlocks = getDataBlocks(codewords, version, ecLevel);
+ // Count total number of data bytes
+ var totalBytes = 0;
+ dataBlocks.forEach(function (dataBlock) {
+ totalBytes += dataBlock.numDataCodewords;
+ });
+ var resultBytes = new Array(totalBytes);
+ var resultOffset = 0;
+ // Error-correct and copy data blocks together into a stream of bytes
+ for (var _i = 0, dataBlocks_1 = dataBlocks; _i < dataBlocks_1.length; _i++) {
+ var dataBlock = dataBlocks_1[_i];
+ var codewordBytes = dataBlock.codewords;
+ var numDataCodewords = dataBlock.numDataCodewords;
+ if (!correctErrors(codewordBytes, numDataCodewords))
+ return null;
+ for (var i = 0; i < numDataCodewords; i++) {
+ resultBytes[resultOffset++] = codewordBytes[i];
+ }
+ }
+ return decodeqrdata_1.decodeQRdata(resultBytes, version.versionNumber, ecLevel.name);
+ }
+ function decode(matrix) {
+ if (matrix == null) {
+ return null;
+ }
+ var result = decodeMatrix(matrix);
+ if (result) {
+ return result;
+ }
+ // Decoding didn't work, try mirroring the QR
+ matrix.mirror();
+ return decodeMatrix(matrix);
+ }
+ exports.decode = decode;
+
+
+/***/ },
+/* 10 */
+/***/ function(module, exports, __webpack_require__) {
+
+ "use strict";
+ var bitstream_1 = __webpack_require__(11);
+ function toAlphaNumericByte(value) {
+ var ALPHANUMERIC_CHARS = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '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',
+ ' ', '$', '%', '*', '+', '-', '.', '/', ':'];
+ if (value >= ALPHANUMERIC_CHARS.length) {
+ throw new Error("Could not decode alphanumeric char");
+ }
+ return ALPHANUMERIC_CHARS[value].charCodeAt(0);
+ }
+ var Mode = (function () {
+ function Mode(characterCountBitsForVersions, bits) {
+ this.characterCountBitsForVersions = characterCountBitsForVersions;
+ this.bits = bits;
+ }
+ Mode.prototype.getCharacterCountBits = function (version) {
+ if (this.characterCountBitsForVersions == null) {
+ throw new Error("Character count doesn't apply to this mode");
+ }
+ var offset;
+ if (version <= 9) {
+ offset = 0;
+ }
+ else if (version <= 26) {
+ offset = 1;
+ }
+ else {
+ offset = 2;
+ }
+ return this.characterCountBitsForVersions[offset];
+ };
+ return Mode;
+ }());
+ var TERMINATOR_MODE = new Mode([0, 0, 0], 0x00); // Not really a mod...
+ var NUMERIC_MODE = new Mode([10, 12, 14], 0x01);
+ var ALPHANUMERIC_MODE = new Mode([9, 11, 13], 0x02);
+ var STRUCTURED_APPEND_MODE = new Mode([0, 0, 0], 0x03); // Not supported
+ var BYTE_MODE = new Mode([8, 16, 16], 0x04);
+ var ECI_MODE = new Mode(null, 0x07); // character counts don't apply
+ var KANJI_MODE = new Mode([8, 10, 12], 0x08);
+ var FNC1_FIRST_POSITION_MODE = new Mode(null, 0x05);
+ var FNC1_SECOND_POSITION_MODE = new Mode(null, 0x09);
+ var HANZI_MODE = new Mode([8, 10, 12], 0x0D);
+ function modeForBits(bits) {
+ switch (bits) {
+ case 0x0:
+ return TERMINATOR_MODE;
+ case 0x1:
+ return NUMERIC_MODE;
+ case 0x2:
+ return ALPHANUMERIC_MODE;
+ case 0x3:
+ return STRUCTURED_APPEND_MODE;
+ case 0x4:
+ return BYTE_MODE;
+ case 0x5:
+ return FNC1_FIRST_POSITION_MODE;
+ case 0x7:
+ return ECI_MODE;
+ case 0x8:
+ return KANJI_MODE;
+ case 0x9:
+ return FNC1_SECOND_POSITION_MODE;
+ case 0xD:
+ // 0xD is defined in GBT 18284-2000, may not be supported in foreign country
+ return HANZI_MODE;
+ default:
+ throw new Error("Couldn't decode mode from byte array");
+ }
+ }
+ function parseECIValue(bits) {
+ var firstByte = bits.readBits(8);
+ if ((firstByte & 0x80) == 0) {
+ // just one byte
+ return firstByte & 0x7F;
+ }
+ if ((firstByte & 0xC0) == 0x80) {
+ // two bytes
+ var secondByte = bits.readBits(8);
+ return ((firstByte & 0x3F) << 8) | secondByte;
+ }
+ if ((firstByte & 0xE0) == 0xC0) {
+ // three bytes
+ var secondThirdBytes = bits.readBits(16);
+ return ((firstByte & 0x1F) << 16) | secondThirdBytes;
+ }
+ throw new Error("Bad ECI bits starting with byte " + firstByte);
+ }
+ function decodeHanziSegment(bits, result, count) {
+ // Don't crash trying to read more bits than we have available.
+ if (count * 13 > bits.available()) {
+ return false;
+ }
+ // Each character will require 2 bytes. Read the characters as 2-byte pairs
+ // and decode as GB2312 afterwards
+ var buffer = new Array(2 * count);
+ var offset = 0;
+ while (count > 0) {
+ // Each 13 bits encodes a 2-byte character
+ var twoBytes = bits.readBits(13);
+ var assembledTwoBytes = (Math.floor(twoBytes / 0x060) << 8) | (twoBytes % 0x060);
+ if (assembledTwoBytes < 0x003BF) {
+ // In the 0xA1A1 to 0xAAFE range
+ assembledTwoBytes += 0x0A1A1;
+ }
+ else {
+ // In the 0xB0A1 to 0xFAFE range
+ assembledTwoBytes += 0x0A6A1;
+ }
+ buffer[offset] = ((assembledTwoBytes >> 8) & 0xFF);
+ buffer[offset + 1] = (assembledTwoBytes & 0xFF);
+ offset += 2;
+ count--;
+ }
+ result.val = buffer;
+ return true;
+ }
+ function decodeNumericSegment(bits, result, count) {
+ // Read three digits at a time
+ while (count >= 3) {
+ // Each 10 bits encodes three digits
+ if (bits.available() < 10) {
+ return false;
+ }
+ var threeDigitsBits = bits.readBits(10);
+ if (threeDigitsBits >= 1000) {
+ return false;
+ }
+ result.val.push(toAlphaNumericByte(Math.floor(threeDigitsBits / 100)));
+ result.val.push(toAlphaNumericByte(Math.floor(threeDigitsBits / 10) % 10));
+ result.val.push(toAlphaNumericByte(threeDigitsBits % 10));
+ count -= 3;
+ }
+ if (count == 2) {
+ // Two digits left over to read, encoded in 7 bits
+ if (bits.available() < 7) {
+ return false;
+ }
+ var twoDigitsBits = bits.readBits(7);
+ if (twoDigitsBits >= 100) {
+ return false;
+ }
+ result.val.push(toAlphaNumericByte(Math.floor(twoDigitsBits / 10)));
+ result.val.push(toAlphaNumericByte(twoDigitsBits % 10));
+ }
+ else if (count == 1) {
+ // One digit left over to read
+ if (bits.available() < 4) {
+ return false;
+ }
+ var digitBits = bits.readBits(4);
+ if (digitBits >= 10) {
+ return false;
+ }
+ result.val.push(toAlphaNumericByte(digitBits));
+ }
+ return true;
+ }
+ function decodeAlphanumericSegment(bits, result, count, fc1InEffect) {
+ // Read two characters at a time
+ var start = result.val.length;
+ while (count > 1) {
+ if (bits.available() < 11) {
+ return false;
+ }
+ var nextTwoCharsBits = bits.readBits(11);
+ result.val.push(toAlphaNumericByte(Math.floor(nextTwoCharsBits / 45)));
+ result.val.push(toAlphaNumericByte(nextTwoCharsBits % 45));
+ count -= 2;
+ }
+ if (count == 1) {
+ // special case: one character left
+ if (bits.available() < 6) {
+ return false;
+ }
+ result.val.push(toAlphaNumericByte(bits.readBits(6)));
+ }
+ // See section 6.4.8.1, 6.4.8.2
+ if (fc1InEffect) {
+ // We need to massage the result a bit if in an FNC1 mode:
+ for (var i = start; i < result.val.length; i++) {
+ if (result.val[i] == '%'.charCodeAt(0)) {
+ if (i < result.val.length - 1 && result.val[i + 1] == '%'.charCodeAt(0)) {
+ // %% is rendered as %
+ result.val = result.val.slice(0, i + 1).concat(result.val.slice(i + 2));
+ }
+ else {
+ // In alpha mode, % should be converted to FNC1 separator 0x1D
+ // THIS IS ALMOST CERTAINLY INVALID
+ result.val[i] = 0x1D;
+ }
+ }
+ }
+ }
+ return true;
+ }
+ function decodeByteSegment(bits, result, count) {
+ // Don't crash trying to read more bits than we have available.
+ if (count << 3 > bits.available()) {
+ return false;
+ }
+ var readBytes = new Array(count);
+ for (var i = 0; i < count; i++) {
+ readBytes[i] = bits.readBits(8);
+ }
+ Array.prototype.push.apply(result.val, readBytes);
+ return true;
+ }
+ var GB2312_SUBSET = 1;
+ // Takes in a byte array, a qr version number and an error correction level.
+ // Returns decoded data.
+ function decodeQRdata(data, version, ecl) {
+ var symbolSequence = -1;
+ var parityData = -1;
+ var bits = new bitstream_1.BitStream(data);
+ var result = { val: [] }; // Have to pass this around so functions can share a reference to a number[]
+ var fc1InEffect = false;
+ var mode;
+ while (mode != TERMINATOR_MODE) {
+ // While still another segment to read...
+ if (bits.available() < 4) {
+ // OK, assume we're done. Really, a TERMINATOR mode should have been recorded here
+ mode = TERMINATOR_MODE;
+ }
+ else {
+ mode = modeForBits(bits.readBits(4)); // mode is encoded by 4 bits
+ }
+ if (mode != TERMINATOR_MODE) {
+ if (mode == FNC1_FIRST_POSITION_MODE || mode == FNC1_SECOND_POSITION_MODE) {
+ // We do little with FNC1 except alter the parsed result a bit according to the spec
+ fc1InEffect = true;
+ }
+ else if (mode == STRUCTURED_APPEND_MODE) {
+ if (bits.available() < 16) {
+ return null;
+ }
+ // not really supported; but sequence number and parity is added later to the result metadata
+ // Read next 8 bits (symbol sequence #) and 8 bits (parity data), then continue
+ symbolSequence = bits.readBits(8);
+ parityData = bits.readBits(8);
+ }
+ else if (mode == ECI_MODE) {
+ // Ignore since we don't do character encoding in JS
+ var value = parseECIValue(bits);
+ if (value < 0 || value > 30) {
+ return null;
+ }
+ }
+ else {
+ // First handle Hanzi mode which does not start with character count
+ if (mode == HANZI_MODE) {
+ //chinese mode contains a sub set indicator right after mode indicator
+ var subset = bits.readBits(4);
+ var countHanzi = bits.readBits(mode.getCharacterCountBits(version));
+ if (subset == GB2312_SUBSET) {
+ if (!decodeHanziSegment(bits, result, countHanzi)) {
+ return null;
+ }
+ }
+ }
+ else {
+ // "Normal" QR code modes:
+ // How many characters will follow, encoded in this mode?
+ var count = bits.readBits(mode.getCharacterCountBits(version));
+ if (mode == NUMERIC_MODE) {
+ if (!decodeNumericSegment(bits, result, count)) {
+ return null;
+ }
+ }
+ else if (mode == ALPHANUMERIC_MODE) {
+ if (!decodeAlphanumericSegment(bits, result, count, fc1InEffect)) {
+ return null;
+ }
+ }
+ else if (mode == BYTE_MODE) {
+ if (!decodeByteSegment(bits, result, count)) {
+ return null;
+ }
+ }
+ else if (mode == KANJI_MODE) {
+ }
+ else {
+ return null;
+ }
+ }
+ }
+ }
+ }
+ return result.val;
+ }
+ exports.decodeQRdata = decodeQRdata;
+
+
+/***/ },
+/* 11 */
+/***/ function(module, exports) {
+
+ "use strict";
+ var BitStream = (function () {
+ function BitStream(bytes) {
+ this.byteOffset = 0;
+ this.bitOffset = 0;
+ this.bytes = bytes;
+ }
+ BitStream.prototype.readBits = function (numBits) {
+ if (numBits < 1 || numBits > 32 || numBits > this.available()) {
+ throw new Error("Cannot read " + numBits.toString() + " bits");
+ }
+ var result = 0;
+ // First, read remainder from current byte
+ if (this.bitOffset > 0) {
+ var bitsLeft = 8 - this.bitOffset;
+ var toRead = numBits < bitsLeft ? numBits : bitsLeft;
+ var bitsToNotRead = bitsLeft - toRead;
+ var mask = (0xFF >> (8 - toRead)) << bitsToNotRead;
+ result = (this.bytes[this.byteOffset] & mask) >> bitsToNotRead;
+ numBits -= toRead;
+ this.bitOffset += toRead;
+ if (this.bitOffset == 8) {
+ this.bitOffset = 0;
+ this.byteOffset++;
+ }
+ }
+ // Next read whole bytes
+ if (numBits > 0) {
+ while (numBits >= 8) {
+ result = (result << 8) | (this.bytes[this.byteOffset] & 0xFF);
+ this.byteOffset++;
+ numBits -= 8;
+ }
+ // Finally read a partial byte
+ if (numBits > 0) {
+ var bitsToNotRead = 8 - numBits;
+ var mask = (0xFF >> bitsToNotRead) << bitsToNotRead;
+ result = (result << numBits) | ((this.bytes[this.byteOffset] & mask) >> bitsToNotRead);
+ this.bitOffset += numBits;
+ }
+ }
+ return result;
+ };
+ BitStream.prototype.available = function () {
+ return 8 * (this.bytes.length - this.byteOffset) - this.bitOffset;
+ };
+ return BitStream;
+ }());
+ exports.BitStream = BitStream;
+
+
+/***/ },
+/* 12 */
+/***/ function(module, exports) {
+
+ "use strict";
+ var ReedSolomonDecoder = (function () {
+ function ReedSolomonDecoder() {
+ this.field = new GenericGF(0x011D, 256, 0); // x^8 + x^4 + x^3 + x^2 + 1
+ }
+ ReedSolomonDecoder.prototype.decode = function (received, twoS) {
+ var poly = new GenericGFPoly(this.field, received);
+ var syndromeCoefficients = new Array(twoS);
+ var noError = true;
+ for (var i = 0; i < twoS; i++) {
+ var evaluation = poly.evaluateAt(this.field.exp(i + this.field.generatorBase));
+ syndromeCoefficients[syndromeCoefficients.length - 1 - i] = evaluation;
+ if (evaluation != 0) {
+ noError = false;
+ }
+ }
+ if (noError) {
+ return true;
+ }
+ var syndrome = new GenericGFPoly(this.field, syndromeCoefficients);
+ var sigmaOmega = this.runEuclideanAlgorithm(this.field.buildMonomial(twoS, 1), syndrome, twoS);
+ if (sigmaOmega == null)
+ return false;
+ var sigma = sigmaOmega[0];
+ var errorLocations = this.findErrorLocations(sigma);
+ if (errorLocations == null)
+ return false;
+ var omega = sigmaOmega[1];
+ var errorMagnitudes = this.findErrorMagnitudes(omega, errorLocations);
+ for (var i = 0; i < errorLocations.length; i++) {
+ var position = received.length - 1 - this.field.log(errorLocations[i]);
+ if (position < 0) {
+ // throw new ReedSolomonException("Bad error location");
+ return false;
+ }
+ received[position] = GenericGF.addOrSubtract(received[position], errorMagnitudes[i]);
+ }
+ return true;
+ };
+ ReedSolomonDecoder.prototype.runEuclideanAlgorithm = function (a, b, R) {
+ // Assume a's degree is >= b's
+ if (a.degree() < b.degree()) {
+ var temp = a;
+ a = b;
+ b = temp;
+ }
+ var rLast = a;
+ var r = b;
+ var tLast = this.field.zero;
+ var t = this.field.one;
+ // Run Euclidean algorithm until r's degree is less than R/2
+ while (r.degree() >= R / 2) {
+ var rLastLast = rLast;
+ var tLastLast = tLast;
+ rLast = r;
+ tLast = t;
+ // Divide rLastLast by rLast, with quotient in q and remainder in r
+ if (rLast.isZero()) {
+ // Oops, Euclidean algorithm already terminated?
+ // throw new ReedSolomonException("r_{i-1} was zero");
+ return null;
+ }
+ r = rLastLast;
+ var q = this.field.zero;
+ var denominatorLeadingTerm = rLast.getCoefficient(rLast.degree());
+ var dltInverse = this.field.inverse(denominatorLeadingTerm);
+ while (r.degree() >= rLast.degree() && !r.isZero()) {
+ var degreeDiff = r.degree() - rLast.degree();
+ var scale = this.field.multiply(r.getCoefficient(r.degree()), dltInverse);
+ q = q.addOrSubtract(this.field.buildMonomial(degreeDiff, scale));
+ r = r.addOrSubtract(rLast.multiplyByMonomial(degreeDiff, scale));
+ }
+ t = q.multiplyPoly(tLast).addOrSubtract(tLastLast);
+ if (r.degree() >= rLast.degree()) {
+ // throw new IllegalStateException("Division algorithm failed to reduce polynomial?");
+ return null;
+ }
+ }
+ var sigmaTildeAtZero = t.getCoefficient(0);
+ if (sigmaTildeAtZero == 0) {
+ // throw new ReedSolomonException("sigmaTilde(0) was zero");
+ return null;
+ }
+ var inverse = this.field.inverse(sigmaTildeAtZero);
+ var sigma = t.multiply(inverse);
+ var omega = r.multiply(inverse);
+ return [sigma, omega];
+ };
+ ReedSolomonDecoder.prototype.findErrorLocations = function (errorLocator) {
+ // This is a direct application of Chien's search
+ var numErrors = errorLocator.degree();
+ if (numErrors == 1) {
+ // shortcut
+ return [errorLocator.getCoefficient(1)];
+ }
+ var result = new Array(numErrors);
+ var e = 0;
+ for (var i = 1; i < this.field.size && e < numErrors; i++) {
+ if (errorLocator.evaluateAt(i) == 0) {
+ result[e] = this.field.inverse(i);
+ e++;
+ }
+ }
+ if (e != numErrors) {
+ // throw new ReedSolomonException("Error locator degree does not match number of roots");
+ return null;
+ }
+ return result;
+ };
+ ReedSolomonDecoder.prototype.findErrorMagnitudes = function (errorEvaluator, errorLocations) {
+ // This is directly applying Forney's Formula
+ var s = errorLocations.length;
+ var result = new Array(s);
+ for (var i = 0; i < s; i++) {
+ var xiInverse = this.field.inverse(errorLocations[i]);
+ var denominator = 1;
+ for (var j = 0; j < s; j++) {
+ if (i != j) {
+ //denominator = field.multiply(denominator,
+ // GenericGF.addOrSubtract(1, field.multiply(errorLocations[j], xiInverse)));
+ // Above should work but fails on some Apple and Linux JDKs due to a Hotspot bug.
+ // Below is a funny-looking workaround from Steven Parkes
+ var term = this.field.multiply(errorLocations[j], xiInverse);
+ var termPlus1 = (term & 0x1) == 0 ? term | 1 : term & ~1;
+ denominator = this.field.multiply(denominator, termPlus1);
+ }
+ }
+ result[i] = this.field.multiply(errorEvaluator.evaluateAt(xiInverse), this.field.inverse(denominator));
+ if (this.field.generatorBase != 0) {
+ result[i] = this.field.multiply(result[i], xiInverse);
+ }
+ }
+ return result;
+ };
+ return ReedSolomonDecoder;
+ }());
+ exports.ReedSolomonDecoder = ReedSolomonDecoder;
+ var GenericGFPoly = (function () {
+ function GenericGFPoly(field, coefficients) {
+ if (coefficients.length == 0) {
+ throw new Error("No coefficients.");
+ }
+ this.field = field;
+ var coefficientsLength = coefficients.length;
+ if (coefficientsLength > 1 && coefficients[0] == 0) {
+ // Leading term must be non-zero for anything except the constant polynomial "0"
+ var firstNonZero = 1;
+ while (firstNonZero < coefficientsLength && coefficients[firstNonZero] == 0) {
+ firstNonZero++;
+ }
+ if (firstNonZero == coefficientsLength) {
+ this.coefficients = field.zero.coefficients;
+ }
+ else {
+ this.coefficients = new Array(coefficientsLength - firstNonZero);
+ /*Array.Copy(coefficients, // Source array
+ firstNonZero, // Source index
+ this.coefficients, // Destination array
+ 0, // Destination index
+ this.coefficients.length); // length*/
+ for (var i = 0; i < this.coefficients.length; i++) {
+ this.coefficients[i] = coefficients[firstNonZero + i];
+ }
+ }
+ }
+ else {
+ this.coefficients = coefficients;
+ }
+ }
+ GenericGFPoly.prototype.evaluateAt = function (a) {
+ var result = 0;
+ if (a == 0) {
+ // Just return the x^0 coefficient
+ return this.getCoefficient(0);
+ }
+ var size = this.coefficients.length;
+ if (a == 1) {
+ // Just the sum of the coefficients
+ this.coefficients.forEach(function (coefficient) {
+ result = GenericGF.addOrSubtract(result, coefficient);
+ });
+ return result;
+ }
+ result = this.coefficients[0];
+ for (var i = 1; i < size; i++) {
+ result = GenericGF.addOrSubtract(this.field.multiply(a, result), this.coefficients[i]);
+ }
+ return result;
+ };
+ GenericGFPoly.prototype.getCoefficient = function (degree) {
+ return this.coefficients[this.coefficients.length - 1 - degree];
+ };
+ GenericGFPoly.prototype.degree = function () {
+ return this.coefficients.length - 1;
+ };
+ GenericGFPoly.prototype.isZero = function () {
+ return this.coefficients[0] == 0;
+ };
+ GenericGFPoly.prototype.addOrSubtract = function (other) {
+ /* TODO, fix this.
+ if (!this.field.Equals(other.field))
+ {
+ throw new Error("GenericGFPolys do not have same GenericGF field");
+ }*/
+ if (this.isZero()) {
+ return other;
+ }
+ if (other.isZero()) {
+ return this;
+ }
+ var smallerCoefficients = this.coefficients;
+ var largerCoefficients = other.coefficients;
+ if (smallerCoefficients.length > largerCoefficients.length) {
+ var temp = smallerCoefficients;
+ smallerCoefficients = largerCoefficients;
+ largerCoefficients = temp;
+ }
+ var sumDiff = new Array(largerCoefficients.length);
+ var lengthDiff = largerCoefficients.length - smallerCoefficients.length;
+ // Copy high-order terms only found in higher-degree polynomial's coefficients
+ ///Array.Copy(largerCoefficients, 0, sumDiff, 0, lengthDiff);
+ for (var i = 0; i < lengthDiff; i++) {
+ sumDiff[i] = largerCoefficients[i];
+ }
+ for (var i = lengthDiff; i < largerCoefficients.length; i++) {
+ sumDiff[i] = GenericGF.addOrSubtract(smallerCoefficients[i - lengthDiff], largerCoefficients[i]);
+ }
+ return new GenericGFPoly(this.field, sumDiff);
+ };
+ GenericGFPoly.prototype.multiply = function (scalar) {
+ if (scalar == 0) {
+ return this.field.zero;
+ }
+ if (scalar == 1) {
+ return this;
+ }
+ var size = this.coefficients.length;
+ var product = new Array(size);
+ for (var i = 0; i < size; i++) {
+ product[i] = this.field.multiply(this.coefficients[i], scalar);
+ }
+ return new GenericGFPoly(this.field, product);
+ };
+ GenericGFPoly.prototype.multiplyPoly = function (other) {
+ /* TODO Fix this.
+ if (!field.Equals(other.field))
+ {
+ throw new Error("GenericGFPolys do not have same GenericGF field");
+ }*/
+ if (this.isZero() || other.isZero()) {
+ return this.field.zero;
+ }
+ var aCoefficients = this.coefficients;
+ var aLength = aCoefficients.length;
+ var bCoefficients = other.coefficients;
+ var bLength = bCoefficients.length;
+ var product = new Array(aLength + bLength - 1);
+ for (var i = 0; i < aLength; i++) {
+ var aCoeff = aCoefficients[i];
+ for (var j = 0; j < bLength; j++) {
+ product[i + j] = GenericGF.addOrSubtract(product[i + j], this.field.multiply(aCoeff, bCoefficients[j]));
+ }
+ }
+ return new GenericGFPoly(this.field, product);
+ };
+ GenericGFPoly.prototype.multiplyByMonomial = function (degree, coefficient) {
+ if (degree < 0) {
+ throw new Error("Invalid degree less than 0");
+ }
+ if (coefficient == 0) {
+ return this.field.zero;
+ }
+ var size = this.coefficients.length;
+ var product = new Array(size + degree);
+ for (var i = 0; i < size; i++) {
+ product[i] = this.field.multiply(this.coefficients[i], coefficient);
+ }
+ return new GenericGFPoly(this.field, product);
+ };
+ return GenericGFPoly;
+ }());
+ var GenericGF = (function () {
+ function GenericGF(primitive, size, genBase) {
+ // ok.
+ this.INITIALIZATION_THRESHOLD = 0;
+ this.initialized = false;
+ this.primitive = primitive;
+ this.size = size;
+ this.generatorBase = genBase;
+ if (size <= this.INITIALIZATION_THRESHOLD) {
+ this.initialize();
+ }
+ }
+ GenericGF.prototype.initialize = function () {
+ this.expTable = new Array(this.size);
+ this.logTable = new Array(this.size);
+ var x = 1;
+ for (var i = 0; i < this.size; i++) {
+ this.expTable[i] = x;
+ x <<= 1; // x = x * 2; we're assuming the generator alpha is 2
+ if (x >= this.size) {
+ x ^= this.primitive;
+ x &= this.size - 1;
+ }
+ }
+ for (var i = 0; i < this.size - 1; i++) {
+ this.logTable[this.expTable[i]] = i;
+ }
+ // logTable[0] == 0 but this should never be used
+ this.zero = new GenericGFPoly(this, [0]);
+ this.one = new GenericGFPoly(this, [1]);
+ this.initialized = true;
+ };
+ GenericGF.addOrSubtract = function (a, b) {
+ return a ^ b;
+ };
+ GenericGF.prototype.checkInit = function () {
+ if (!this.initialized)
+ this.initialize();
+ };
+ GenericGF.prototype.multiply = function (a, b) {
+ this.checkInit();
+ if (a == 0 || b == 0) {
+ return 0;
+ }
+ return this.expTable[(this.logTable[a] + this.logTable[b]) % (this.size - 1)];
+ };
+ GenericGF.prototype.exp = function (a) {
+ this.checkInit();
+ return this.expTable[a];
+ };
+ GenericGF.prototype.log = function (a) {
+ this.checkInit();
+ if (a == 0) {
+ throw new Error("Can't take log(0)");
+ }
+ return this.logTable[a];
+ };
+ GenericGF.prototype.inverse = function (a) {
+ this.checkInit();
+ if (a == 0) {
+ throw new Error("Can't invert 0");
+ }
+ return this.expTable[this.size - this.logTable[a] - 1];
+ };
+ GenericGF.prototype.buildMonomial = function (degree, coefficient) {
+ this.checkInit();
+ if (degree < 0) {
+ throw new Error("Invalid monomial degree less than 0");
+ }
+ if (coefficient == 0) {
+ return this.zero;
+ }
+ var coefficients = new Array(degree + 1);
+ coefficients[0] = coefficient;
+ return new GenericGFPoly(this, coefficients);
+ };
+ return GenericGF;
+ }());
+
+
+/***/ }
+/******/ ])
});
-
-// Support: IE<8
-// Prevent attribute/property "interpolation"
-// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
-if ( !assert(function( div ) {
- div.innerHTML = "";
- return div.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( div ) {
- div.innerHTML = "";
- div.firstChild.setAttribute( "value", "" );
- return div.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( div ) {
- return div.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;
-jQuery.expr[ ":" ] = jQuery.expr.pseudos;
-jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort;
-jQuery.text = Sizzle.getText;
-jQuery.isXMLDoc = Sizzle.isXML;
-jQuery.contains = Sizzle.contains;
-
-
-
-var dir = function( elem, dir, until ) {
- var matched = [],
- truncate = until !== undefined;
-
- while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) {
- if ( elem.nodeType === 1 ) {
- if ( truncate && jQuery( elem ).is( until ) ) {
- break;
- }
- matched.push( elem );
- }
- }
- return matched;
-};
-
-
-var siblings = function( n, elem ) {
- var matched = [];
-
- for ( ; n; n = n.nextSibling ) {
- if ( n.nodeType === 1 && n !== elem ) {
- matched.push( n );
- }
- }
-
- return matched;
-};
-
-
-var rneedsContext = jQuery.expr.match.needsContext;
-
-var rsingleTag = ( /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/ );
-
-
-
-var risSimple = /^.[^:#\[\.,]*$/;
-
-// Implement the identical functionality for filter and not
-function winnow( elements, qualifier, not ) {
- if ( jQuery.isFunction( qualifier ) ) {
- return jQuery.grep( elements, function( elem, i ) {
- /* jshint -W018 */
- return !!qualifier.call( elem, i, elem ) !== not;
- } );
-
- }
-
- if ( qualifier.nodeType ) {
- return jQuery.grep( elements, function( elem ) {
- return ( elem === qualifier ) !== not;
- } );
-
- }
-
- if ( typeof qualifier === "string" ) {
- if ( risSimple.test( qualifier ) ) {
- return jQuery.filter( qualifier, elements, not );
- }
-
- qualifier = jQuery.filter( qualifier, elements );
- }
-
- return jQuery.grep( elements, function( elem ) {
- return ( indexOf.call( qualifier, elem ) > -1 ) !== not;
- } );
-}
-
-jQuery.filter = function( expr, elems, not ) {
- var elem = elems[ 0 ];
-
- if ( not ) {
- expr = ":not(" + expr + ")";
- }
-
- return elems.length === 1 && elem.nodeType === 1 ?
- jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
- jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
- return elem.nodeType === 1;
- } ) );
-};
-
-jQuery.fn.extend( {
- find: function( selector ) {
- var i,
- len = this.length,
- ret = [],
- 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;
- }
- }
- } ) );
- }
-
- for ( i = 0; i < len; i++ ) {
- jQuery.find( selector, self[ i ], ret );
- }
-
- // Needed because $( selector, context ) becomes $( context ).find( selector )
- ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
- ret.selector = this.selector ? this.selector + " " + selector : selector;
- return 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 to avoid XSS via location.hash (#9521)
- // Strict HTML recognition (#11290: must start with <)
- rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
-
- init = jQuery.fn.init = function( selector, context, root ) {
- var match, elem;
-
- // HANDLE: $(""), $(null), $(undefined), $(false)
- if ( !selector ) {
- return this;
- }
-
- // Method init() accepts an alternate rootjQuery
- // so migrate can support jQuery.sub (gh-2101)
- root = root || rootjQuery;
-
- // Handle HTML strings
- if ( typeof selector === "string" ) {
- if ( selector[ 0 ] === "<" &&
- selector[ selector.length - 1 ] === ">" &&
- selector.length >= 3 ) {
-
- // Assume that strings that start and end with <> are HTML and skip the regex check
- match = [ null, selector, null ];
-
- } else {
- match = rquickExpr.exec( selector );
- }
-
- // Match html or make sure no context is specified for #id
- if ( match && ( match[ 1 ] || !context ) ) {
-
- // HANDLE: $(html) -> $(array)
- if ( match[ 1 ] ) {
- context = context instanceof jQuery ? context[ 0 ] : context;
-
- // Option to run scripts is true for back-compat
- // Intentionally let the error be thrown if parseHTML is not present
- jQuery.merge( this, jQuery.parseHTML(
- match[ 1 ],
- context && context.nodeType ? context.ownerDocument || context : document,
- true
- ) );
-
- // HANDLE: $(html, props)
- if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) {
- for ( match in context ) {
-
- // Properties of context are called as methods if possible
- if ( jQuery.isFunction( this[ match ] ) ) {
- this[ match ]( context[ match ] );
-
- // ...and otherwise set as attributes
- } else {
- this.attr( match, context[ match ] );
- }
- }
- }
-
- return this;
-
- // HANDLE: $(#id)
- } else {
- elem = document.getElementById( match[ 2 ] );
-
- // Support: Blackberry 4.6
- // gEBID returns nodes no longer in the document (#6963)
- if ( elem && elem.parentNode ) {
-
- // Inject the element directly into the jQuery object
- this.length = 1;
- this[ 0 ] = elem;
- }
-
- this.context = document;
- this.selector = selector;
- 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.context = this[ 0 ] = selector;
- this.length = 1;
- return this;
-
- // HANDLE: $(function)
- // Shortcut for document ready
- } else if ( jQuery.isFunction( selector ) ) {
- return root.ready !== undefined ?
- root.ready( selector ) :
-
- // Execute immediately if ready is not present
- selector( jQuery );
- }
-
- if ( selector.selector !== undefined ) {
- this.selector = selector.selector;
- this.context = selector.context;
- }
-
- 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 = [],
- pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
- jQuery( selectors, context || this.context ) :
- 0;
-
- for ( ; i < l; i++ ) {
- for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) {
-
- // Always skip document fragments
- if ( cur.nodeType < 11 && ( pos ?
- pos.index( cur ) > -1 :
-
- // Don't pass non-elements to Sizzle
- cur.nodeType === 1 &&
- jQuery.find.matchesSelector( cur, selectors ) ) ) {
-
- matched.push( cur );
- break;
- }
- }
- }
-
- return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched );
- },
-
- // Determine the position of an element within the set
- index: function( elem ) {
-
- // No argument, return index in parent
- if ( !elem ) {
- return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1;
- }
-
- // Index in selector
- if ( typeof elem === "string" ) {
- return indexOf.call( jQuery( elem ), this[ 0 ] );
- }
-
- // Locate the position of the desired element
- return indexOf.call( this,
-
- // If it receives a jQuery object, the first element is used
- elem.jquery ? elem[ 0 ] : elem
- );
- },
-
- add: function( selector, context ) {
- return this.pushStack(
- jQuery.uniqueSort(
- jQuery.merge( this.get(), jQuery( selector, context ) )
- )
- );
- },
-
- addBack: function( selector ) {
- return this.add( selector == null ?
- this.prevObject : this.prevObject.filter( selector )
- );
- }
-} );
-
-function sibling( cur, dir ) {
- while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {}
- return cur;
-}
-
-jQuery.each( {
- parent: function( elem ) {
- var parent = elem.parentNode;
- return parent && parent.nodeType !== 11 ? parent : null;
- },
- parents: function( elem ) {
- return dir( elem, "parentNode" );
- },
- parentsUntil: function( elem, i, until ) {
- return dir( elem, "parentNode", until );
- },
- next: function( elem ) {
- return sibling( elem, "nextSibling" );
- },
- prev: function( elem ) {
- return sibling( elem, "previousSibling" );
- },
- nextAll: function( elem ) {
- return dir( elem, "nextSibling" );
- },
- prevAll: function( elem ) {
- return dir( elem, "previousSibling" );
- },
- nextUntil: function( elem, i, until ) {
- return dir( elem, "nextSibling", until );
- },
- prevUntil: function( elem, i, until ) {
- return dir( elem, "previousSibling", until );
- },
- siblings: function( elem ) {
- return siblings( ( elem.parentNode || {} ).firstChild, elem );
- },
- children: function( elem ) {
- return siblings( elem.firstChild );
- },
- contents: function( elem ) {
- return elem.contentDocument || jQuery.merge( [], elem.childNodes );
- }
-}, function( name, fn ) {
- jQuery.fn[ name ] = function( until, selector ) {
- var matched = jQuery.map( this, fn, until );
-
- if ( name.slice( -5 ) !== "Until" ) {
- selector = until;
- }
-
- if ( selector && typeof selector === "string" ) {
- matched = jQuery.filter( selector, matched );
- }
-
- if ( this.length > 1 ) {
-
- // Remove duplicates
- if ( !guaranteedUnique[ name ] ) {
- jQuery.uniqueSort( matched );
- }
-
- // Reverse order for parents* and prev-derivatives
- if ( rparentsprev.test( name ) ) {
- matched.reverse();
- }
- }
-
- return this.pushStack( matched );
- };
-} );
-var rnotwhite = ( /\S+/g );
-
-
-
-// Convert String-formatted options into Object-formatted ones
-function createOptions( options ) {
- var object = {};
- jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) {
- object[ flag ] = true;
- } );
- return object;
-}
-
-/*
- * Create a callback list using the following parameters:
- *
- * options: an optional list of space-separated options that will change how
- * the callback list behaves or a more traditional option object
- *
- * By default a callback list will act like an event callback list and can be
- * "fired" multiple times.
- *
- * Possible options:
- *
- * once: will ensure the callback list can only be fired once (like a Deferred)
- *
- * memory: will keep track of previous values and will call any callback added
- * after the list has been fired right away with the latest "memorized"
- * values (like a Deferred)
- *
- * unique: will ensure a callback can only be added once (no duplicate in the list)
- *
- * stopOnFalse: interrupt callings when a callback returns false
- *
- */
-jQuery.Callbacks = function( options ) {
-
- // Convert options from String-formatted to Object-formatted if needed
- // (we check in cache first)
- options = typeof options === "string" ?
- createOptions( options ) :
- jQuery.extend( {}, options );
-
- var // Flag to know if list is currently firing
- firing,
-
- // Last fire value for non-forgettable lists
- memory,
-
- // Flag to know if list was already fired
- fired,
-
- // Flag to prevent firing
- locked,
-
- // Actual callback list
- list = [],
-
- // Queue of execution data for repeatable lists
- queue = [],
-
- // Index of currently firing callback (modified by add/remove as needed)
- firingIndex = -1,
-
- // Fire callbacks
- fire = function() {
-
- // Enforce single-firing
- locked = options.once;
-
- // Execute callbacks for all pending executions,
- // respecting firingIndex overrides and runtime changes
- fired = firing = true;
- for ( ; queue.length; firingIndex = -1 ) {
- memory = queue.shift();
- while ( ++firingIndex < list.length ) {
-
- // Run callback and check for early termination
- if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false &&
- options.stopOnFalse ) {
-
- // Jump to end and forget the data so .add doesn't re-fire
- firingIndex = list.length;
- memory = false;
- }
- }
- }
-
- // Forget the data if we're done with it
- if ( !options.memory ) {
- memory = false;
- }
-
- firing = false;
-
- // Clean up if we're done firing for good
- if ( locked ) {
-
- // Keep an empty list if we have data for future add calls
- if ( memory ) {
- list = [];
-
- // Otherwise, this object is spent
- } else {
- list = "";
- }
- }
- },
-
- // Actual Callbacks object
- self = {
-
- // Add a callback or a collection of callbacks to the list
- add: function() {
- if ( list ) {
-
- // If we have memory from a past run, we should fire after adding
- if ( memory && !firing ) {
- firingIndex = list.length - 1;
- queue.push( memory );
- }
-
- ( function add( args ) {
- jQuery.each( args, function( _, arg ) {
- if ( jQuery.isFunction( arg ) ) {
- if ( !options.unique || !self.has( arg ) ) {
- list.push( arg );
- }
- } else if ( arg && arg.length && jQuery.type( arg ) !== "string" ) {
-
- // Inspect recursively
- add( arg );
- }
- } );
- } )( arguments );
-
- if ( memory && !firing ) {
- fire();
- }
- }
- return this;
- },
-
- // Remove a callback from the list
- remove: function() {
- jQuery.each( arguments, function( _, arg ) {
- var index;
- while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
- list.splice( index, 1 );
-
- // Handle firing indexes
- if ( index <= firingIndex ) {
- firingIndex--;
- }
- }
- } );
- return this;
- },
-
- // Check if a given callback is in the list.
- // If no argument is given, return whether or not list has callbacks attached.
- has: function( fn ) {
- return fn ?
- jQuery.inArray( fn, list ) > -1 :
- list.length > 0;
- },
-
- // Remove all callbacks from the list
- empty: function() {
- if ( list ) {
- list = [];
- }
- return this;
- },
-
- // Disable .fire and .add
- // Abort any current/pending executions
- // Clear all callbacks and values
- disable: function() {
- locked = queue = [];
- list = memory = "";
- return this;
- },
- disabled: function() {
- return !list;
- },
-
- // Disable .fire
- // Also disable .add unless we have memory (since it would have no effect)
- // Abort any pending executions
- lock: function() {
- locked = queue = [];
- if ( !memory ) {
- 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;
-};
-
-
-jQuery.extend( {
-
- Deferred: function( func ) {
- var tuples = [
-
- // action, add listener, listener list, final state
- [ "resolve", "done", jQuery.Callbacks( "once memory" ), "resolved" ],
- [ "reject", "fail", jQuery.Callbacks( "once memory" ), "rejected" ],
- [ "notify", "progress", jQuery.Callbacks( "memory" ) ]
- ],
- state = "pending",
- promise = {
- state: function() {
- return state;
- },
- always: function() {
- deferred.done( arguments ).fail( arguments );
- return this;
- },
- then: function( /* fnDone, fnFail, fnProgress */ ) {
- var fns = arguments;
- return jQuery.Deferred( function( newDefer ) {
- jQuery.each( tuples, function( i, tuple ) {
- var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];
-
- // deferred[ done | fail | progress ] for forwarding actions to newDefer
- deferred[ tuple[ 1 ] ]( function() {
- var returned = fn && fn.apply( this, arguments );
- if ( returned && jQuery.isFunction( returned.promise ) ) {
- returned.promise()
- .progress( newDefer.notify )
- .done( newDefer.resolve )
- .fail( newDefer.reject );
- } else {
- newDefer[ tuple[ 0 ] + "With" ](
- this === promise ? newDefer.promise() : this,
- fn ? [ returned ] : arguments
- );
- }
- } );
- } );
- fns = null;
- } ).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 = {};
-
- // Keep pipe for back-compat
- promise.pipe = promise.then;
-
- // Add list-specific methods
- jQuery.each( tuples, function( i, tuple ) {
- var list = tuple[ 2 ],
- stateString = tuple[ 3 ];
-
- // promise[ done | fail | progress ] = list.add
- promise[ tuple[ 1 ] ] = list.add;
-
- // Handle state
- if ( stateString ) {
- list.add( function() {
-
- // state = [ resolved | rejected ]
- state = stateString;
-
- // [ reject_list | resolve_list ].disable; progress_list.lock
- }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
- }
-
- // deferred[ resolve | reject | notify ]
- deferred[ tuple[ 0 ] ] = function() {
- deferred[ tuple[ 0 ] + "With" ]( this === deferred ? promise : this, arguments );
- return this;
- };
- 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( subordinate /* , ..., subordinateN */ ) {
- var i = 0,
- resolveValues = slice.call( arguments ),
- length = resolveValues.length,
-
- // the count of uncompleted subordinates
- remaining = length !== 1 ||
- ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
-
- // the master Deferred.
- // If resolveValues consist of only a single Deferred, just use that.
- deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
-
- // Update function for both resolve and progress values
- updateFunc = function( i, contexts, values ) {
- return function( value ) {
- contexts[ i ] = this;
- values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value;
- if ( values === progressValues ) {
- deferred.notifyWith( contexts, values );
- } else if ( !( --remaining ) ) {
- deferred.resolveWith( contexts, values );
- }
- };
- },
-
- progressValues, progressContexts, resolveContexts;
-
- // Add listeners to Deferred subordinates; treat others as resolved
- if ( length > 1 ) {
- progressValues = new Array( length );
- progressContexts = new Array( length );
- resolveContexts = new Array( length );
- for ( ; i < length; i++ ) {
- if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
- resolveValues[ i ].promise()
- .progress( updateFunc( i, progressContexts, progressValues ) )
- .done( updateFunc( i, resolveContexts, resolveValues ) )
- .fail( deferred.reject );
- } else {
- --remaining;
- }
- }
- }
-
- // If we're not waiting on anything, resolve the master
- if ( !remaining ) {
- deferred.resolveWith( resolveContexts, resolveValues );
- }
-
- return deferred.promise();
- }
-} );
-
-
-// The deferred used on DOM ready
-var readyList;
-
-jQuery.fn.ready = function( fn ) {
-
- // Add the callback
- jQuery.ready.promise().done( fn );
-
- return this;
-};
-
-jQuery.extend( {
-
- // Is the DOM ready to be used? Set to true once it occurs.
- isReady: false,
-
- // A counter to track how many items to wait for before
- // the ready event fires. See #6781
- readyWait: 1,
-
- // Hold (or release) the ready event
- holdReady: function( hold ) {
- if ( hold ) {
- jQuery.readyWait++;
- } else {
- jQuery.ready( true );
- }
- },
-
- // Handle when the DOM is ready
- ready: function( wait ) {
-
- // Abort if there are pending holds or we're already ready
- if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
- return;
- }
-
- // Remember that the DOM is ready
- jQuery.isReady = true;
-
- // If a normal DOM Ready event fired, decrement, and wait if need be
- if ( wait !== true && --jQuery.readyWait > 0 ) {
- return;
- }
-
- // If there are functions bound, to execute
- readyList.resolveWith( document, [ jQuery ] );
-
- // Trigger any bound ready events
- if ( jQuery.fn.triggerHandler ) {
- jQuery( document ).triggerHandler( "ready" );
- jQuery( document ).off( "ready" );
- }
- }
-} );
-
-/**
- * The ready event handler and self cleanup method
- */
-function completed() {
- document.removeEventListener( "DOMContentLoaded", completed );
- window.removeEventListener( "load", completed );
- jQuery.ready();
-}
-
-jQuery.ready.promise = function( obj ) {
- if ( !readyList ) {
-
- readyList = jQuery.Deferred();
-
- // Catch cases where $(document).ready() is called
- // after the browser event has already occurred.
- // Support: IE9-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 );
- }
- }
- return readyList.promise( obj );
-};
-
-// Kick off the DOM ready check even if the user does not
-jQuery.ready.promise();
-
-
-
-
-// Multifunctional method to get and set values of a collection
-// The value/s can optionally be executed if it's a function
-var access = function( elems, fn, key, value, chainable, emptyGet, raw ) {
- var i = 0,
- len = elems.length,
- bulk = key == null;
-
- // Sets many values
- if ( jQuery.type( key ) === "object" ) {
- chainable = true;
- for ( i in key ) {
- access( elems, fn, i, key[ i ], true, emptyGet, raw );
- }
-
- // Sets one value
- } else if ( value !== undefined ) {
- chainable = true;
-
- if ( !jQuery.isFunction( value ) ) {
- raw = true;
- }
-
- if ( bulk ) {
-
- // Bulk operations run against the entire set
- if ( raw ) {
- fn.call( elems, value );
- fn = null;
-
- // ...except when executing function values
- } else {
- bulk = fn;
- fn = function( elem, key, value ) {
- return bulk.call( jQuery( elem ), value );
- };
- }
- }
-
- if ( fn ) {
- for ( ; i < len; i++ ) {
- fn(
- elems[ i ], key, raw ?
- value :
- value.call( elems[ i ], i, fn( elems[ i ], key ) )
- );
- }
- }
- }
-
- return chainable ?
- elems :
-
- // Gets
- bulk ?
- fn.call( elems ) :
- len ? fn( elems[ 0 ], key ) : emptyGet;
-};
-var acceptData = function( owner ) {
-
- // Accepts only:
- // - Node
- // - Node.ELEMENT_NODE
- // - Node.DOCUMENT_NODE
- // - Object
- // - Any
- /* jshint -W018 */
- return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType );
-};
-
-
-
-
-function Data() {
- this.expando = jQuery.expando + Data.uid++;
-}
-
-Data.uid = 1;
-
-Data.prototype = {
-
- register: function( owner, initial ) {
- var value = initial || {};
-
- // 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, non-writable property
- // configurability must be true to allow the property to be
- // deleted with the delete operator
- } else {
- Object.defineProperty( owner, this.expando, {
- value: value,
- writable: true,
- configurable: true
- } );
- }
- return owner[ this.expando ];
- },
- cache: function( owner ) {
-
- // 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 ) ) {
- return {};
- }
-
- // 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
- if ( typeof data === "string" ) {
- cache[ data ] = value;
-
- // Handle: [ owner, { properties } ] args
- } else {
-
- // Copy the properties one-by-one to the cache object
- for ( prop in data ) {
- cache[ prop ] = data[ prop ];
- }
- }
- return cache;
- },
- get: function( owner, key ) {
- return key === undefined ?
- this.cache( owner ) :
- owner[ this.expando ] && owner[ this.expando ][ key ];
- },
- access: function( owner, key, value ) {
- var stored;
-
- // 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 ) ) {
-
- stored = this.get( owner, key );
-
- return stored !== undefined ?
- stored : this.get( owner, jQuery.camelCase( 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, name, camel,
- cache = owner[ this.expando ];
-
- if ( cache === undefined ) {
- return;
- }
-
- if ( key === undefined ) {
- this.register( owner );
-
- } else {
-
- // Support array or space separated string of keys
- if ( jQuery.isArray( key ) ) {
-
- // If "name" is an array of keys...
- // When data is initially created, via ("key", "val") signature,
- // keys will be converted to camelCase.
- // Since there is no way to tell _how_ a key was added, remove
- // both plain key and camelCase key. #12786
- // This will only penalize the array argument path.
- name = key.concat( key.map( jQuery.camelCase ) );
- } else {
- camel = jQuery.camelCase( key );
-
- // Try the string as a key before any manipulation
- if ( key in cache ) {
- name = [ key, camel ];
- } else {
-
- // If a key with the spaces exists, use it.
- // Otherwise, create an array by matching non-whitespace
- name = camel;
- name = name in cache ?
- [ name ] : ( name.match( rnotwhite ) || [] );
- }
- }
-
- i = name.length;
-
- while ( i-- ) {
- delete cache[ name[ 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://code.google.com/p/chromium/issues/detail?id=378607
- if ( owner.nodeType ) {
- owner[ this.expando ] = undefined;
- } else {
- delete owner[ this.expando ];
- }
- }
- },
- hasData: function( owner ) {
- var cache = owner[ this.expando ];
- return cache !== undefined && !jQuery.isEmptyObject( cache );
- }
-};
-var dataPriv = new Data();
-
-var dataUser = new Data();
-
-
-
-// Implementation Summary
-//
-// 1. Enforce API surface and semantic compatibility with 1.9.x branch
-// 2. Improve the module's maintainability by reducing the storage
-// paths to a single mechanism.
-// 3. Use the same single mechanism to support "private" and "user" data.
-// 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData)
-// 5. Avoid exposing implementation details on user objects (eg. expando properties)
-// 6. Provide a clear path for implementation upgrade to WeakMap in 2014
-
-var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
- rmultiDash = /[A-Z]/g;
-
-function dataAttr( elem, key, data ) {
- var name;
-
- // If nothing was found internally, try to fetch any
- // data from the HTML5 data-* attribute
- if ( data === undefined && elem.nodeType === 1 ) {
- name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase();
- data = elem.getAttribute( name );
-
- if ( typeof data === "string" ) {
- try {
- data = data === "true" ? true :
- data === "false" ? false :
- data === "null" ? null :
-
- // Only convert to a number if it doesn't change the string
- +data + "" === data ? +data :
- rbrace.test( data ) ? jQuery.parseJSON( data ) :
- data;
- } catch ( e ) {}
-
- // Make sure we set the data so it isn't changed later
- dataUser.set( elem, key, data );
- } else {
- data = undefined;
- }
- }
- return data;
-}
-
-jQuery.extend( {
- hasData: function( elem ) {
- return dataUser.hasData( elem ) || dataPriv.hasData( elem );
- },
-
- data: function( elem, name, data ) {
- return dataUser.access( elem, name, data );
- },
-
- removeData: function( elem, name ) {
- dataUser.remove( elem, name );
- },
-
- // TODO: Now that all calls to _data and _removeData have been replaced
- // with direct calls to dataPriv methods, these can be deprecated.
- _data: function( elem, name, data ) {
- return dataPriv.access( elem, name, data );
- },
-
- _removeData: function( elem, name ) {
- dataPriv.remove( elem, name );
- }
-} );
-
-jQuery.fn.extend( {
- data: function( key, value ) {
- var i, name, data,
- elem = this[ 0 ],
- attrs = elem && elem.attributes;
-
- // Gets all values
- if ( key === undefined ) {
- if ( this.length ) {
- data = dataUser.get( elem );
-
- if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) {
- i = attrs.length;
- while ( i-- ) {
-
- // Support: IE11+
- // The attrs elements can be null (#14894)
- if ( attrs[ i ] ) {
- name = attrs[ i ].name;
- if ( name.indexOf( "data-" ) === 0 ) {
- name = jQuery.camelCase( name.slice( 5 ) );
- dataAttr( elem, name, data[ name ] );
- }
- }
- }
- dataPriv.set( elem, "hasDataAttrs", true );
- }
- }
-
- return data;
- }
-
- // Sets multiple values
- if ( typeof key === "object" ) {
- return this.each( function() {
- dataUser.set( this, key );
- } );
- }
-
- return access( this, function( value ) {
- var data, camelKey;
-
- // 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
- // with the key as-is
- data = dataUser.get( elem, key ) ||
-
- // Try to find dashed key if it exists (gh-2779)
- // This is for 2.2.x only
- dataUser.get( elem, key.replace( rmultiDash, "-$&" ).toLowerCase() );
-
- if ( data !== undefined ) {
- return data;
- }
-
- camelKey = jQuery.camelCase( key );
-
- // Attempt to get data from the cache
- // with the key camelized
- data = dataUser.get( elem, camelKey );
- if ( data !== undefined ) {
- return data;
- }
-
- // Attempt to "discover" the data in
- // HTML5 custom data-* attrs
- data = dataAttr( elem, camelKey, undefined );
- if ( data !== undefined ) {
- return data;
- }
-
- // We tried really hard, but the data doesn't exist.
- return;
- }
-
- // Set the data...
- camelKey = jQuery.camelCase( key );
- this.each( function() {
-
- // First, attempt to store a copy or reference of any
- // data that might've been store with a camelCased key.
- var data = dataUser.get( this, camelKey );
-
- // For HTML5 data-* attribute interop, we have to
- // store property names with dashes in a camelCase form.
- // This might not apply to all properties...*
- dataUser.set( this, camelKey, value );
-
- // *... In the case of properties that might _actually_
- // have dashes, we need to also store a copy of that
- // unchanged property.
- if ( key.indexOf( "-" ) > -1 && data !== undefined ) {
- dataUser.set( this, key, value );
- }
- } );
- }, null, value, arguments.length > 1, null, true );
- },
-
- removeData: function( key ) {
- return this.each( function() {
- dataUser.remove( this, key );
- } );
- }
-} );
-
-
-jQuery.extend( {
- queue: function( elem, type, data ) {
- var queue;
-
- if ( elem ) {
- type = ( type || "fx" ) + "queue";
- queue = dataPriv.get( elem, type );
-
- // Speed up dequeue by getting out quickly if this is just a lookup
- if ( data ) {
- if ( !queue || jQuery.isArray( data ) ) {
- queue = dataPriv.access( elem, type, jQuery.makeArray( data ) );
- } else {
- queue.push( data );
- }
- }
- return queue || [];
- }
- },
-
- dequeue: function( elem, type ) {
- type = type || "fx";
-
- var queue = jQuery.queue( elem, type ),
- startLength = queue.length,
- fn = queue.shift(),
- hooks = jQuery._queueHooks( elem, type ),
- next = function() {
- jQuery.dequeue( elem, type );
- };
-
- // If the fx queue is dequeued, always remove the progress sentinel
- if ( fn === "inprogress" ) {
- fn = queue.shift();
- startLength--;
- }
-
- if ( fn ) {
-
- // Add a progress sentinel to prevent the fx queue from being
- // automatically dequeued
- if ( type === "fx" ) {
- queue.unshift( "inprogress" );
- }
-
- // Clear up the last queue stop function
- delete hooks.stop;
- fn.call( elem, next, hooks );
- }
-
- if ( !startLength && hooks ) {
- hooks.empty.fire();
- }
- },
-
- // Not public - generate a queueHooks object, or return the current one
- _queueHooks: function( elem, type ) {
- var key = type + "queueHooks";
- return dataPriv.get( elem, key ) || dataPriv.access( elem, key, {
- empty: jQuery.Callbacks( "once memory" ).add( function() {
- dataPriv.remove( elem, [ type + "queue", key ] );
- } )
- } );
- }
-} );
-
-jQuery.fn.extend( {
- queue: function( type, data ) {
- var setter = 2;
-
- if ( typeof type !== "string" ) {
- data = type;
- type = "fx";
- setter--;
- }
-
- if ( arguments.length < setter ) {
- return jQuery.queue( this[ 0 ], type );
- }
-
- return data === undefined ?
- this :
- this.each( function() {
- var queue = jQuery.queue( this, type, data );
-
- // Ensure a hooks for this queue
- jQuery._queueHooks( this, type );
-
- if ( type === "fx" && queue[ 0 ] !== "inprogress" ) {
- jQuery.dequeue( this, type );
- }
- } );
- },
- dequeue: function( type ) {
- return this.each( function() {
- jQuery.dequeue( this, type );
- } );
- },
- clearQueue: function( type ) {
- return this.queue( type || "fx", [] );
- },
-
- // Get a promise resolved when queues of a certain type
- // are emptied (fx is the type by default)
- promise: function( type, obj ) {
- var tmp,
- count = 1,
- defer = jQuery.Deferred(),
- elements = this,
- i = this.length,
- resolve = function() {
- if ( !( --count ) ) {
- defer.resolveWith( elements, [ elements ] );
- }
- };
-
- if ( typeof type !== "string" ) {
- obj = type;
- type = undefined;
- }
- type = type || "fx";
-
- while ( i-- ) {
- tmp = dataPriv.get( elements[ i ], type + "queueHooks" );
- if ( tmp && tmp.empty ) {
- count++;
- tmp.empty.add( resolve );
- }
- }
- resolve();
- return defer.promise( obj );
- }
-} );
-var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source;
-
-var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" );
-
-
-var cssExpand = [ "Top", "Right", "Bottom", "Left" ];
-
-var isHidden = function( elem, el ) {
-
- // isHidden might be called from jQuery#filter function;
- // in that case, element will be second argument
- elem = el || elem;
- return jQuery.css( elem, "display" ) === "none" ||
- !jQuery.contains( elem.ownerDocument, elem );
- };
-
-
-
-function adjustCSS( elem, prop, valueParts, tween ) {
- var adjusted,
- scale = 1,
- maxIterations = 20,
- currentValue = tween ?
- function() { return tween.cur(); } :
- function() { return jQuery.css( elem, prop, "" ); },
- initial = currentValue(),
- unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
-
- // Starting value computation is required for potential unit mismatches
- initialInUnit = ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) &&
- rcssNum.exec( jQuery.css( elem, prop ) );
-
- if ( initialInUnit && initialInUnit[ 3 ] !== unit ) {
-
- // Trust units reported by jQuery.css
- unit = unit || initialInUnit[ 3 ];
-
- // Make sure we update the tween properties later on
- valueParts = valueParts || [];
-
- // Iteratively approximate from a nonzero starting point
- initialInUnit = +initial || 1;
-
- do {
-
- // If previous iteration zeroed out, double until we get *something*.
- // Use string for doubling so we don't accidentally see scale as unchanged below
- scale = scale || ".5";
-
- // Adjust and apply
- initialInUnit = initialInUnit / scale;
- jQuery.style( elem, prop, initialInUnit + unit );
-
- // Update scale, tolerating zero or NaN from tween.cur()
- // Break the loop if scale is unchanged or perfect, or if we've just had enough.
- } while (
- scale !== ( scale = currentValue() / initial ) && scale !== 1 && --maxIterations
- );
- }
-
- if ( valueParts ) {
- initialInUnit = +initialInUnit || +initial || 0;
-
- // Apply relative offset (+=/-=) if specified
- adjusted = valueParts[ 1 ] ?
- initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] :
- +valueParts[ 2 ];
- if ( tween ) {
- tween.unit = unit;
- tween.start = initialInUnit;
- tween.end = adjusted;
- }
- }
- return adjusted;
-}
-var rcheckableType = ( /^(?:checkbox|radio)$/i );
-
-var rtagName = ( /<([\w:-]+)/ );
-
-var rscriptType = ( /^$|\/(?:java|ecma)script/i );
-
-
-
-// We have to close these tags to support XHTML (#13200)
-var wrapMap = {
-
- // Support: IE9
- option: [ 1, "" ],
-
- // XHTML parsers do not magically insert elements in the
- // same way that tag soup parsers do. So we cannot shorten
- // this by omitting or other required elements.
- thead: [ 1, "" ],
- col: [ 2, "" ],
- tr: [ 2, "" ],
- td: [ 3, "" ],
-
- _default: [ 0, "", "" ]
-};
-
-// Support: IE9
-wrapMap.optgroup = wrapMap.option;
-
-wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
-wrapMap.th = wrapMap.td;
-
-
-function getAll( context, tag ) {
-
- // Support: IE9-11+
- // Use typeof to avoid zero-argument method invocation on host objects (#15151)
- var ret = typeof context.getElementsByTagName !== "undefined" ?
- context.getElementsByTagName( tag || "*" ) :
- typeof context.querySelectorAll !== "undefined" ?
- context.querySelectorAll( tag || "*" ) :
- [];
-
- return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
- jQuery.merge( [ context ], ret ) :
- ret;
-}
-
-
-// Mark scripts as having already been evaluated
-function setGlobalEval( elems, refElements ) {
- var i = 0,
- l = elems.length;
-
- for ( ; i < l; i++ ) {
- dataPriv.set(
- elems[ i ],
- "globalEval",
- !refElements || dataPriv.get( refElements[ i ], "globalEval" )
- );
- }
-}
-
-
-var rhtml = /<|?\w+;/;
-
-function buildFragment( elems, context, scripts, selection, ignored ) {
- var elem, tmp, tag, wrap, contains, j,
- fragment = context.createDocumentFragment(),
- nodes = [],
- i = 0,
- l = elems.length;
-
- for ( ; i < l; i++ ) {
- elem = elems[ i ];
-
- if ( elem || elem === 0 ) {
-
- // Add nodes directly
- if ( jQuery.type( elem ) === "object" ) {
-
- // Support: Android<4.1, PhantomJS<2
- // 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.1, PhantomJS<2
- // push.apply(_, arraylike) throws on ancient WebKit
- jQuery.merge( nodes, tmp.childNodes );
-
- // Remember the top-level container
- tmp = fragment.firstChild;
-
- // Ensure the created nodes are orphaned (#12392)
- tmp.textContent = "";
- }
- }
- }
-
- // Remove wrapper from fragment
- fragment.textContent = "";
-
- i = 0;
- while ( ( elem = nodes[ i++ ] ) ) {
-
- // Skip elements already in the context collection (trac-4087)
- if ( selection && jQuery.inArray( elem, selection ) > -1 ) {
- if ( ignored ) {
- ignored.push( elem );
- }
- continue;
- }
-
- contains = jQuery.contains( elem.ownerDocument, elem );
-
- // Append to fragment
- tmp = getAll( fragment.appendChild( elem ), "script" );
-
- // Preserve script evaluation history
- if ( contains ) {
- setGlobalEval( tmp );
- }
-
- // Capture executables
- if ( scripts ) {
- j = 0;
- while ( ( elem = tmp[ j++ ] ) ) {
- if ( rscriptType.test( elem.type || "" ) ) {
- scripts.push( elem );
- }
- }
- }
- }
-
- return fragment;
-}
-
-
-( function() {
- var fragment = document.createDocumentFragment(),
- div = fragment.appendChild( document.createElement( "div" ) ),
- input = document.createElement( "input" );
-
- // Support: Android 4.0-4.3, Safari<=5.1
- // 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: Safari<=5.1, Android<4.2
- // Older WebKit doesn't clone checked state correctly in fragments
- support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;
-
- // Support: IE<=11+
- // Make sure textarea (and checkbox) defaultValue is properly cloned
- div.innerHTML = "";
- support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;
-} )();
-
-
-var
- rkeyEvent = /^key/,
- rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/,
- rtypenamespace = /^([^.]*)(?:\.(.+)|)/;
-
-function returnTrue() {
- return true;
-}
-
-function returnFalse() {
- return false;
-}
-
-// Support: IE9
-// See #13393 for more info
-function safeActiveElement() {
- try {
- return document.activeElement;
- } catch ( err ) { }
-}
-
-function on( elem, types, selector, data, fn, one ) {
- var origFn, type;
-
- // Types can be a map of types/handlers
- if ( typeof types === "object" ) {
-
- // ( types-Object, selector, data )
- if ( typeof selector !== "string" ) {
-
- // ( types-Object, data )
- data = data || selector;
- selector = undefined;
- }
- for ( type in types ) {
- on( elem, type, selector, data, types[ type ], one );
- }
- return elem;
- }
-
- if ( data == null && fn == null ) {
-
- // ( types, fn )
- fn = selector;
- data = selector = undefined;
- } else if ( fn == null ) {
- if ( typeof selector === "string" ) {
-
- // ( types, selector, fn )
- fn = data;
- data = undefined;
- } else {
-
- // ( types, data, fn )
- fn = data;
- data = selector;
- selector = undefined;
- }
- }
- if ( fn === false ) {
- fn = returnFalse;
- } else if ( !fn ) {
- return elem;
- }
-
- if ( one === 1 ) {
- origFn = fn;
- fn = function( event ) {
-
- // Can use an empty set, since event contains the info
- jQuery().off( event );
- return origFn.apply( this, arguments );
- };
-
- // Use same guid so caller can remove using origFn
- fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
- }
- return elem.each( function() {
- jQuery.event.add( this, types, fn, data, selector );
- } );
-}
-
-/*
- * Helper functions for managing events -- not part of the public interface.
- * Props to Dean Edwards' addEvent library for many of the ideas.
- */
-jQuery.event = {
-
- global: {},
-
- add: function( elem, types, handler, data, selector ) {
-
- var handleObjIn, eventHandle, tmp,
- events, t, handleObj,
- special, handlers, type, namespaces, origType,
- elemData = dataPriv.get( elem );
-
- // Don't attach events to noData or text/comment nodes (but allow plain objects)
- if ( !elemData ) {
- return;
- }
-
- // Caller can pass in an object of custom data in lieu of the handler
- if ( handler.handler ) {
- handleObjIn = handler;
- handler = handleObjIn.handler;
- selector = handleObjIn.selector;
- }
-
- // Make sure that the handler has a unique ID, used to find/remove it later
- if ( !handler.guid ) {
- handler.guid = jQuery.guid++;
- }
-
- // Init the element's event structure and main handler, if this is the first
- if ( !( events = elemData.events ) ) {
- events = elemData.events = {};
- }
- if ( !( eventHandle = elemData.handle ) ) {
- eventHandle = elemData.handle = function( e ) {
-
- // Discard the second event of a jQuery.event.trigger() and
- // when an event is called after a page has unloaded
- return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ?
- jQuery.event.dispatch.apply( elem, arguments ) : undefined;
- };
- }
-
- // Handle multiple events separated by a space
- types = ( types || "" ).match( rnotwhite ) || [ "" ];
- t = types.length;
- while ( t-- ) {
- tmp = rtypenamespace.exec( types[ t ] ) || [];
- type = origType = tmp[ 1 ];
- namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort();
-
- // There *must* be a type, no attaching namespace-only handlers
- if ( !type ) {
- continue;
- }
-
- // If event changes its type, use the special event handlers for the changed type
- special = jQuery.event.special[ type ] || {};
-
- // If selector defined, determine special event api type, otherwise given type
- type = ( selector ? special.delegateType : special.bindType ) || type;
-
- // Update special based on newly reset type
- special = jQuery.event.special[ type ] || {};
-
- // handleObj is passed to all event handlers
- handleObj = jQuery.extend( {
- type: type,
- origType: origType,
- data: data,
- handler: handler,
- guid: handler.guid,
- selector: selector,
- needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
- namespace: namespaces.join( "." )
- }, handleObjIn );
-
- // Init the event handler queue if we're the first
- if ( !( handlers = events[ type ] ) ) {
- handlers = events[ type ] = [];
- handlers.delegateCount = 0;
-
- // Only use addEventListener if the special events handler returns false
- if ( !special.setup ||
- special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
-
- if ( elem.addEventListener ) {
- elem.addEventListener( type, eventHandle );
- }
- }
- }
-
- if ( special.add ) {
- special.add.call( elem, handleObj );
-
- if ( !handleObj.handler.guid ) {
- handleObj.handler.guid = handler.guid;
- }
- }
-
- // Add to the element's handler list, delegates in front
- if ( selector ) {
- handlers.splice( handlers.delegateCount++, 0, handleObj );
- } else {
- handlers.push( handleObj );
- }
-
- // Keep track of which events have ever been used, for event optimization
- jQuery.event.global[ type ] = true;
- }
-
- },
-
- // Detach an event or set of events from an element
- remove: function( elem, types, handler, selector, mappedTypes ) {
-
- var j, origCount, tmp,
- events, t, handleObj,
- special, handlers, type, namespaces, origType,
- elemData = dataPriv.hasData( elem ) && dataPriv.get( elem );
-
- if ( !elemData || !( events = elemData.events ) ) {
- return;
- }
-
- // Once for each type.namespace in types; type may be omitted
- types = ( types || "" ).match( rnotwhite ) || [ "" ];
- t = types.length;
- while ( t-- ) {
- tmp = rtypenamespace.exec( types[ t ] ) || [];
- type = origType = tmp[ 1 ];
- namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort();
-
- // Unbind all events (on this namespace, if provided) for the element
- if ( !type ) {
- for ( type in events ) {
- jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
- }
- continue;
- }
-
- special = jQuery.event.special[ type ] || {};
- type = ( selector ? special.delegateType : special.bindType ) || type;
- handlers = events[ type ] || [];
- tmp = tmp[ 2 ] &&
- new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" );
-
- // Remove matching events
- origCount = j = handlers.length;
- while ( j-- ) {
- handleObj = handlers[ j ];
-
- if ( ( mappedTypes || origType === handleObj.origType ) &&
- ( !handler || handler.guid === handleObj.guid ) &&
- ( !tmp || tmp.test( handleObj.namespace ) ) &&
- ( !selector || selector === handleObj.selector ||
- selector === "**" && handleObj.selector ) ) {
- handlers.splice( j, 1 );
-
- if ( handleObj.selector ) {
- handlers.delegateCount--;
- }
- if ( special.remove ) {
- special.remove.call( elem, handleObj );
- }
- }
- }
-
- // Remove generic event handler if we removed something and no more handlers exist
- // (avoids potential for endless recursion during removal of special event handlers)
- if ( origCount && !handlers.length ) {
- if ( !special.teardown ||
- special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
-
- jQuery.removeEvent( elem, type, elemData.handle );
- }
-
- delete events[ type ];
- }
- }
-
- // Remove data and the expando if it's no longer used
- if ( jQuery.isEmptyObject( events ) ) {
- dataPriv.remove( elem, "handle events" );
- }
- },
-
- dispatch: function( event ) {
-
- // Make a writable jQuery.Event from the native event object
- event = jQuery.event.fix( event );
-
- var i, j, ret, matched, handleObj,
- handlerQueue = [],
- args = slice.call( arguments ),
- handlers = ( dataPriv.get( this, "events" ) || {} )[ event.type ] || [],
- special = jQuery.event.special[ event.type ] || {};
-
- // Use the fix-ed jQuery.Event rather than the (read-only) native event
- args[ 0 ] = event;
- event.delegateTarget = this;
-
- // Call the preDispatch hook for the mapped type, and let it bail if desired
- if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
- return;
- }
-
- // Determine handlers
- handlerQueue = jQuery.event.handlers.call( this, event, handlers );
-
- // Run delegates first; they may want to stop propagation beneath us
- i = 0;
- while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) {
- event.currentTarget = matched.elem;
-
- j = 0;
- while ( ( handleObj = matched.handlers[ j++ ] ) &&
- !event.isImmediatePropagationStopped() ) {
-
- // Triggered event must either 1) have no namespace, or 2) have namespace(s)
- // a subset or equal to those in the bound event (both can have no namespace).
- if ( !event.rnamespace || event.rnamespace.test( handleObj.namespace ) ) {
-
- event.handleObj = handleObj;
- event.data = handleObj.data;
-
- ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle ||
- handleObj.handler ).apply( matched.elem, args );
-
- if ( ret !== undefined ) {
- if ( ( event.result = ret ) === false ) {
- event.preventDefault();
- event.stopPropagation();
- }
- }
- }
- }
- }
-
- // Call the postDispatch hook for the mapped type
- if ( special.postDispatch ) {
- special.postDispatch.call( this, event );
- }
-
- return event.result;
- },
-
- handlers: function( event, handlers ) {
- var i, matches, sel, handleObj,
- handlerQueue = [],
- delegateCount = handlers.delegateCount,
- cur = event.target;
-
- // Support (at least): Chrome, IE9
- // Find delegate handlers
- // Black-hole SVG