/* Minification failed. Returning unminified contents.
(19349,25-26): run-time error JS1195: Expected expression: )
(19349,28-29): run-time error JS1195: Expected expression: >
(19359,14-15): run-time error JS1195: Expected expression: ,
(19362,6-7): run-time error JS1195: Expected expression: )
(19367,19-20): run-time error JS1004: Expected ';': {
(19991,3-4): run-time error JS1195: Expected expression: )
(19991,6-7): run-time error JS1195: Expected expression: >
(20095,48-49): run-time error JS1100: Expected ',': =
(20152,35-36): run-time error JS1100: Expected ',': =
(20165,22-23): run-time error JS1195: Expected expression: .
(20165,23-24): run-time error JS1010: Expected identifier: .
(20165,24-25): run-time error JS1010: Expected identifier: .
(20165,59-60): run-time error JS1004: Expected ';': )
(20170,60-61): run-time error JS1100: Expected ',': =
(20170,63-64): run-time error JS1002: Syntax error: ,
(20170,72-73): run-time error JS1100: Expected ',': =
(20204,32-37): run-time error JS1195: Expected expression: class
(20205,67-68): run-time error JS1004: Expected ';': {
(20290,32-33): run-time error JS1004: Expected ';': {
(20302,39-40): run-time error JS1004: Expected ';': {
(20319,25-26): run-time error JS1004: Expected ';': {
(20325,37-38): run-time error JS1004: Expected ';': {
(20341,28-29): run-time error JS1004: Expected ';': {
(20362,58-59): run-time error JS1014: Invalid character: `
(20362,64-65): run-time error JS1193: Expected ',' or ')': {
(20362,87-88): run-time error JS1195: Expected expression: )
(20362,88-89): run-time error JS1014: Invalid character: `
(20388,28-29): run-time error JS1004: Expected ';': {
(20394,58-59): run-time error JS1014: Invalid character: `
(20394,68-69): run-time error JS1193: Expected ',' or ')': :
(20396,58-59): run-time error JS1014: Invalid character: `
(20396,68-69): run-time error JS1193: Expected ',' or ')': :
(20399,19-20): run-time error JS1004: Expected ';': {
(20412,31-32): run-time error JS1004: Expected ';': {
(20432,29-30): run-time error JS1004: Expected ';': {
(20436,25-26): run-time error JS1004: Expected ';': {
(20444,29-30): run-time error JS1004: Expected ';': {
(20448,22-23): run-time error JS1004: Expected ';': {
(20458,40-41): run-time error JS1004: Expected ';': {
(20474,65-66): run-time error JS1004: Expected ';': {
(20504,5-6): run-time error JS1002: Syntax error: }
(20507,29-34): run-time error JS1195: Expected expression: class
(20508,61-62): run-time error JS1004: Expected ';': {
(20509,23-24): run-time error JS1197: Too many errors. The file might not be a JavaScript file: ,
(20502,13-30): run-time error JS1018: 'return' statement outside of function: return res_params
(20484,17-34): run-time error JS1018: 'return' statement outside of function: return res_params
(20462,17-23): run-time error JS1018: 'return' statement outside of function: return
(20460,17-23): run-time error JS1018: 'return' statement outside of function: return
(20455,13-25): run-time error JS1018: 'return' statement outside of function: return false
(20454,17-28): run-time error JS1018: 'return' statement outside of function: return true
(20452,17-28): run-time error JS1018: 'return' statement outside of function: return true
(20450,17-29): run-time error JS1018: 'return' statement outside of function: return false
(20422,21-27): run-time error JS1018: 'return' statement outside of function: return
(20418,21-27): run-time error JS1018: 'return' statement outside of function: return
(20426,17-23): run-time error JS1018: 'return' statement outside of function: return
(20414,17-23): run-time error JS1018: 'return' statement outside of function: return
(20392,17-23): run-time error JS1018: 'return' statement outside of function: return
(20390,17-23): run-time error JS1018: 'return' statement outside of function: return
(20385,13-32): run-time error JS1018: 'return' statement outside of function: return this.element
(20327,17-23): run-time error JS1018: 'return' statement outside of function: return
(20316,13-24): run-time error JS1018: 'return' statement outside of function: return time
(20308,17-52): run-time error JS1018: 'return' statement outside of function: return this.params["start-at"] || 0
(20306,17-37): run-time error JS1018: 'return' statement outside of function: return this.duration
(20304,17-52): run-time error JS1018: 'return' statement outside of function: return this.params["start-at"] || 0
(20299,13-46): run-time error JS1018: 'return' statement outside of function: return percentage(time, duration)
(20296,17-25): run-time error JS1018: 'return' statement outside of function: return 0
(20294,17-27): run-time error JS1018: 'return' statement outside of function: return 100
(20292,17-25): run-time error JS1018: 'return' statement outside of function: return 0
(20263,17-23): run-time error JS1018: 'return' statement outside of function: return
(20207,17-23): run-time error JS1018: 'return' statement outside of function: return
 */
/*!
 * jQuery JavaScript Library v1.12.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:17Z
 */

(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 deletedIds = [];

var document = window.document;

var slice = deletedIds.slice;

var concat = deletedIds.concat;

var push = deletedIds.push;

var indexOf = deletedIds.indexOf;

var class2type = {};

var toString = class2type.toString;

var hasOwn = class2type.hasOwnProperty;

var support = {};



var
	version = "1.12.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, IE<9
	// 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: deletedIds.sort,
	splice: deletedIds.splice
};

jQuery.extend = jQuery.fn.extend = function() {
	var src, copyIsArray, copy, name, options, 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() {},

	// See test/unit/core.js for details concerning isFunction.
	// Since version 1.3, DOM methods and functions like alert
	// aren't supported. They return false on IE (#2968).
	isFunction: function( obj ) {
		return jQuery.type( obj ) === "function";
	},

	isArray: Array.isArray || function( obj ) {
		return jQuery.type( obj ) === "array";
	},

	isWindow: function( obj ) {
		/* jshint eqeqeq: false */
		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;
	},

	isEmptyObject: function( obj ) {
		var name;
		for ( name in obj ) {
			return false;
		}
		return true;
	},

	isPlainObject: function( obj ) {
		var key;

		// Must be an Object.
		// Because of IE, we also have to check the presence of the constructor property.
		// Make sure that DOM nodes and window objects don't pass through, as well
		if ( !obj || jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
			return false;
		}

		try {

			// Not own constructor property must be Object
			if ( obj.constructor &&
				!hasOwn.call( obj, "constructor" ) &&
				!hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
				return false;
			}
		} catch ( e ) {

			// IE8,9 Will throw exceptions on certain host objects #9897
			return false;
		}

		// Support: IE<9
		// Handle iteration over inherited properties before own properties.
		if ( !support.ownFirst ) {
			for ( key in obj ) {
				return hasOwn.call( obj, key );
			}
		}

		// 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 );
	},

	type: function( obj ) {
		if ( obj == null ) {
			return obj + "";
		}
		return typeof obj === "object" || typeof obj === "function" ?
			class2type[ toString.call( obj ) ] || "object" :
			typeof obj;
	},

	// Workarounds based on findings by Jim Driscoll
	// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
	globalEval: function( data ) {
		if ( data && jQuery.trim( data ) ) {

			// We use execScript on Internet Explorer
			// We use an anonymous function so that context is window
			// rather than jQuery in Firefox
			( window.execScript || function( data ) {
				window[ "eval" ].call( window, data ); // jscs:ignore requireDotNotation
			} )( data );
		}
	},

	// Convert dashed to camelCase; used by the css and data modules
	// 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, IE<9
	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 ) {
		var len;

		if ( arr ) {
			if ( indexOf ) {
				return indexOf.call( arr, elem, i );
			}

			len = arr.length;
			i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;

			for ( ; i < len; i++ ) {

				// Skip accessing in sparse arrays
				if ( i in arr && arr[ i ] === elem ) {
					return i;
				}
			}
		}

		return -1;
	},

	merge: function( first, second ) {
		var len = +second.length,
			j = 0,
			i = first.length;

		while ( j < len ) {
			first[ i++ ] = second[ j++ ];
		}

		// Support: IE<9
		// Workaround casting of .length to NaN on otherwise arraylike objects (e.g., NodeLists)
		if ( len !== len ) {
			while ( second[ j ] !== undefined ) {
				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 args, proxy, tmp;

		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: function() {
		return +( new Date() );
	},

	// 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 ] = deletedIds[ 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 = "<a id='" + expando + "'></a>" +
				"<select id='" + expando + "-\r\\' msallowcapture=''>" +
				"<option selected=''></option></select>";

			// Support: IE8, Opera 11-12.16
			// Nothing should be selected when empty strings follow ^= or $= or *=
			// The test attribute must be unknown in Opera but "safe" for WinRT
			// 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: <number>) matching elements by id
			for ( ; i !== len && (elem = elems[i]) != null; i++ ) {
				if ( byElement && elem ) {
					j = 0;
					if ( !context && elem.ownerDocument !== document ) {
						setDocument( elem );
						xml = !documentIsHTML;
					}
					while ( (matcher = elementMatchers[j++]) ) {
						if ( matcher( elem, context || document, xml) ) {
							results.push( elem );
							break;
						}
					}
					if ( outermost ) {
						dirruns = dirrunsUnique;
					}
				}

				// Track unmatched elements for set filters
				if ( bySet ) {
					// They will have gone through all possible matchers
					if ( (elem = !matcher && elem) ) {
						matchedCount--;
					}

					// Lengthen the array for every element, matched or not
					if ( seed ) {
						unmatched.push( elem );
					}
				}
			}

			// `i` is now the count of elements visited above, and adding it to `matchedCount`
			// makes the latter nonnegative.
			matchedCount += i;

			// Apply set filters to unmatched elements
			// NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount`
			// equals `i`), unless we didn't visit _any_ elements in the above loop because we have
			// no element matchers and no seed.
			// Incrementing an initially-string "0" `i` allows `i` to remain a string only in that
			// case, which will result in a "00" `matchedCount` that differs from `i` but is also
			// numerically zero.
			if ( bySet && i !== matchedCount ) {
				j = 0;
				while ( (matcher = setMatchers[j++]) ) {
					matcher( unmatched, setMatched, context, xml );
				}

				if ( seed ) {
					// Reintegrate element matches to eliminate the need for sorting
					if ( matchedCount > 0 ) {
						while ( i-- ) {
							if ( !(unmatched[i] || setMatched[i]) ) {
								setMatched[i] = pop.call( results );
							}
						}
					}

					// Discard index placeholder values to get only actual matches
					setMatched = condense( setMatched );
				}

				// Add matches to results
				push.apply( results, setMatched );

				// Seedless set matches succeeding multiple successful matchers stipulate sorting
				if ( outermost && !seed && setMatched.length > 0 &&
					( matchedCount + setMatchers.length ) > 1 ) {

					Sizzle.uniqueSort( results );
				}
			}

			// Override manipulation of globals by nested matchers
			if ( outermost ) {
				dirruns = dirrunsUnique;
				outermostContext = contextBackup;
			}

			return unmatched;
		};

	return bySet ?
		markFunction( superMatcher ) :
		superMatcher;
}

compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) {
	var i,
		setMatchers = [],
		elementMatchers = [],
		cached = compilerCache[ selector + " " ];

	if ( !cached ) {
		// Generate a function of recursive functions that can be used to check each element
		if ( !match ) {
			match = tokenize( selector );
		}
		i = match.length;
		while ( i-- ) {
			cached = matcherFromTokens( match[i] );
			if ( cached[ expando ] ) {
				setMatchers.push( cached );
			} else {
				elementMatchers.push( cached );
			}
		}

		// Cache the compiled function
		cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );

		// Save selector and tokenization
		cached.selector = selector;
	}
	return cached;
};

/**
 * A low-level selection function that works with Sizzle's compiled
 *  selector functions
 * @param {String|Function} selector A selector or a pre-compiled
 *  selector function built with Sizzle.compile
 * @param {Element} context
 * @param {Array} [results]
 * @param {Array} [seed] A set of elements to match against
 */
select = Sizzle.select = function( selector, context, results, seed ) {
	var i, tokens, token, type, find,
		compiled = typeof selector === "function" && selector,
		match = !seed && tokenize( (selector = compiled.selector || selector) );

	results = results || [];

	// Try to minimize operations if there is only one selector in the list and no seed
	// (the latter of which guarantees us context)
	if ( match.length === 1 ) {

		// Reduce context if the leading compound selector is an ID
		tokens = match[0] = match[0].slice( 0 );
		if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
				support.getById && context.nodeType === 9 && documentIsHTML &&
				Expr.relative[ tokens[1].type ] ) {

			context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
			if ( !context ) {
				return results;

			// Precompiled matchers will still verify ancestry, so step up a level
			} else if ( compiled ) {
				context = context.parentNode;
			}

			selector = selector.slice( tokens.shift().value.length );
		}

		// Fetch a seed set for right-to-left matching
		i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
		while ( i-- ) {
			token = tokens[i];

			// Abort if we hit a combinator
			if ( Expr.relative[ (type = token.type) ] ) {
				break;
			}
			if ( (find = Expr.find[ type ]) ) {
				// Search, expanding context for leading sibling combinators
				if ( (seed = find(
					token.matches[0].replace( runescape, funescape ),
					rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context
				)) ) {

					// If seed is empty or no tokens remain, we can return early
					tokens.splice( i, 1 );
					selector = seed.length && toSelector( tokens );
					if ( !selector ) {
						push.apply( results, seed );
						return results;
					}

					break;
				}
			}
		}
	}

	// Compile and execute a filtering function if one is not provided
	// Provide `match` to avoid retokenization if we modified the selector above
	( compiled || compile( selector, match ) )(
		seed,
		context,
		!documentIsHTML,
		results,
		!context || rsibling.test( selector ) && testContext( context.parentNode ) || context
	);
	return results;
};

// One-time assignments

// Sort stability
support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;

// Support: Chrome 14-35+
// Always assume duplicates if they aren't passed to the comparison function
support.detectDuplicates = !!hasDuplicate;

// Initialize against the default document
setDocument();

// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
// Detached nodes confoundingly follow *each other*
support.sortDetached = assert(function( div1 ) {
	// Should return 1, but returns 4 (following)
	return div1.compareDocumentPosition( document.createElement("div") ) & 1;
});

// 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 = "<a href='#'></a>";
	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 = "<input/>";
	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 ( jQuery.inArray( elem, qualifier ) > -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,
			ret = [],
			self = this,
			len = self.length;

		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 <tag> 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;
		}

		// 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.charAt( 0 ) === "<" &&
				selector.charAt( 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;

					// 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 ] );

					// Check parentNode to catch when Blackberry 4.6 returns
					// nodes that are no longer in the document #6963
					if ( elem && elem.parentNode ) {

						// Handle the case where IE and Opera return items
						// by name instead of ID
						if ( elem.id !== match[ 2 ] ) {
							return rootjQuery.find( selector );
						}

						// Otherwise, we 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 typeof 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 i,
			targets = jQuery( target, this ),
			len = targets.length;

		return this.filter( function() {
			for ( i = 0; i < len; 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 matched set of elements
	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 jQuery.inArray( this[ 0 ], jQuery( elem ) );
		}

		// Locate the position of the desired element
		return jQuery.inArray(

			// If it receives a jQuery object, the first element is used
			elem.jquery ? elem[ 0 ] : elem, this );
	},

	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 ) {
	do {
		cur = cur[ dir ];
	} while ( cur && 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 jQuery.nodeName( elem, "iframe" ) ?
			elem.contentDocument || elem.contentWindow.document :
			jQuery.merge( [], elem.childNodes );
	}
}, function( name, fn ) {
	jQuery.fn[ name ] = function( until, selector ) {
		var ret = jQuery.map( this, fn, until );

		if ( name.slice( -5 ) !== "Until" ) {
			selector = until;
		}

		if ( selector && typeof selector === "string" ) {
			ret = jQuery.filter( selector, ret );
		}

		if ( this.length > 1 ) {

			// Remove duplicates
			if ( !guaranteedUnique[ name ] ) {
				ret = jQuery.uniqueSort( ret );
			}

			// Reverse order for parents* and prev-derivatives
			if ( rparentsprev.test( name ) ) {
				ret = ret.reverse();
			}
		}

		return this.pushStack( ret );
	};
} );
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 = true;
				if ( !memory ) {
					self.disable();
				}
				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" );
		}
	}
} );

/**
 * Clean-up method for dom ready events
 */
function detach() {
	if ( document.addEventListener ) {
		document.removeEventListener( "DOMContentLoaded", completed );
		window.removeEventListener( "load", completed );

	} else {
		document.detachEvent( "onreadystatechange", completed );
		window.detachEvent( "onload", completed );
	}
}

/**
 * The ready event handler and self cleanup method
 */
function completed() {

	// readyState === "complete" is good enough for us to call the dom ready in oldIE
	if ( document.addEventListener ||
		window.event.type === "load" ||
		document.readyState === "complete" ) {

		detach();
		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: IE6-10
		// 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 );

		// Standards-based browsers support DOMContentLoaded
		} else if ( document.addEventListener ) {

			// Use the handy event callback
			document.addEventListener( "DOMContentLoaded", completed );

			// A fallback to window.onload, that will always work
			window.addEventListener( "load", completed );

		// If IE event model is used
		} else {

			// Ensure firing before onload, maybe late but safe also for iframes
			document.attachEvent( "onreadystatechange", completed );

			// A fallback to window.onload, that will always work
			window.attachEvent( "onload", completed );

			// If IE and not a frame
			// continually check to see if the document is ready
			var top = false;

			try {
				top = window.frameElement == null && document.documentElement;
			} catch ( e ) {}

			if ( top && top.doScroll ) {
				( function doScrollCheck() {
					if ( !jQuery.isReady ) {

						try {

							// Use the trick by Diego Perini
							// http://javascript.nwbox.com/IEContentLoaded/
							top.doScroll( "left" );
						} catch ( e ) {
							return window.setTimeout( doScrollCheck, 50 );
						}

						// detach all dom ready events
						detach();

						// and execute any waiting functions
						jQuery.ready();
					}
				} )();
			}
		}
	}
	return readyList.promise( obj );
};

// Kick off the DOM ready check even if the user does not
jQuery.ready.promise();




// Support: IE<9
// Iteration over object's inherited properties before its own
var i;
for ( i in jQuery( support ) ) {
	break;
}
support.ownFirst = i === "0";

// Note: most support tests are defined in their respective modules.
// false until the test is run
support.inlineBlockNeedsLayout = false;

// Execute ASAP in case we need to set body.style.zoom
jQuery( function() {

	// Minified: var a,b,c,d
	var val, div, body, container;

	body = document.getElementsByTagName( "body" )[ 0 ];
	if ( !body || !body.style ) {

		// Return for frameset docs that don't have a body
		return;
	}

	// Setup
	div = document.createElement( "div" );
	container = document.createElement( "div" );
	container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px";
	body.appendChild( container ).appendChild( div );

	if ( typeof div.style.zoom !== "undefined" ) {

		// Support: IE<8
		// Check if natively block-level elements act like inline-block
		// elements when setting their display to 'inline' and giving
		// them layout
		div.style.cssText = "display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1";

		support.inlineBlockNeedsLayout = val = div.offsetWidth === 3;
		if ( val ) {

			// Prevent IE 6 from affecting layout for positioned elements #11048
			// Prevent IE from shrinking the body in IE 7 mode #12869
			// Support: IE<8
			body.style.zoom = 1;
		}
	}

	body.removeChild( container );
} );


( function() {
	var div = document.createElement( "div" );

	// Support: IE<9
	support.deleteExpando = true;
	try {
		delete div.test;
	} catch ( e ) {
		support.deleteExpando = false;
	}

	// Null elements to avoid leaks in IE.
	div = null;
} )();
var acceptData = function( elem ) {
	var noData = jQuery.noData[ ( elem.nodeName + " " ).toLowerCase() ],
		nodeType = +elem.nodeType || 1;

	// Do not set data on non-element DOM nodes because it will not be cleared (#8335).
	return nodeType !== 1 && nodeType !== 9 ?
		false :

		// Nodes accept data unless otherwise specified; rejection can be conditional
		!noData || noData !== true && elem.getAttribute( "classid" ) === noData;
};




var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
	rmultiDash = /([A-Z])/g;

function dataAttr( elem, key, data ) {

	// If nothing was found internally, try to fetch any
	// data from the HTML5 data-* attribute
	if ( data === undefined && elem.nodeType === 1 ) {

		var name = "data-" + key.replace( rmultiDash, "-$1" ).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
			jQuery.data( elem, key, data );

		} else {
			data = undefined;
		}
	}

	return data;
}

// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
	var name;
	for ( name in obj ) {

		// if the public data object is empty, the private is still empty
		if ( name === "data" && jQuery.isEmptyObject( obj[ name ] ) ) {
			continue;
		}
		if ( name !== "toJSON" ) {
			return false;
		}
	}

	return true;
}

function internalData( elem, name, data, pvt /* Internal Use Only */ ) {
	if ( !acceptData( elem ) ) {
		return;
	}

	var ret, thisCache,
		internalKey = jQuery.expando,

		// We have to handle DOM nodes and JS objects differently because IE6-7
		// can't GC object references properly across the DOM-JS boundary
		isNode = elem.nodeType,

		// Only DOM nodes need the global jQuery cache; JS object data is
		// attached directly to the object so GC can occur automatically
		cache = isNode ? jQuery.cache : elem,

		// Only defining an ID for JS objects if its cache already exists allows
		// the code to shortcut on the same path as a DOM node with no cache
		id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;

	// Avoid doing any more work than we need to when trying to get data on an
	// object that has no data at all
	if ( ( !id || !cache[ id ] || ( !pvt && !cache[ id ].data ) ) &&
		data === undefined && typeof name === "string" ) {
		return;
	}

	if ( !id ) {

		// Only DOM nodes need a new unique ID for each element since their data
		// ends up in the global cache
		if ( isNode ) {
			id = elem[ internalKey ] = deletedIds.pop() || jQuery.guid++;
		} else {
			id = internalKey;
		}
	}

	if ( !cache[ id ] ) {

		// Avoid exposing jQuery metadata on plain JS objects when the object
		// is serialized using JSON.stringify
		cache[ id ] = isNode ? {} : { toJSON: jQuery.noop };
	}

	// An object can be passed to jQuery.data instead of a key/value pair; this gets
	// shallow copied over onto the existing cache
	if ( typeof name === "object" || typeof name === "function" ) {
		if ( pvt ) {
			cache[ id ] = jQuery.extend( cache[ id ], name );
		} else {
			cache[ id ].data = jQuery.extend( cache[ id ].data, name );
		}
	}

	thisCache = cache[ id ];

	// jQuery data() is stored in a separate object inside the object's internal data
	// cache in order to avoid key collisions between internal data and user-defined
	// data.
	if ( !pvt ) {
		if ( !thisCache.data ) {
			thisCache.data = {};
		}

		thisCache = thisCache.data;
	}

	if ( data !== undefined ) {
		thisCache[ jQuery.camelCase( name ) ] = data;
	}

	// Check for both converted-to-camel and non-converted data property names
	// If a data property was specified
	if ( typeof name === "string" ) {

		// First Try to find as-is property data
		ret = thisCache[ name ];

		// Test for null|undefined property data
		if ( ret == null ) {

			// Try to find the camelCased property
			ret = thisCache[ jQuery.camelCase( name ) ];
		}
	} else {
		ret = thisCache;
	}

	return ret;
}

function internalRemoveData( elem, name, pvt ) {
	if ( !acceptData( elem ) ) {
		return;
	}

	var thisCache, i,
		isNode = elem.nodeType,

		// See jQuery.data for more information
		cache = isNode ? jQuery.cache : elem,
		id = isNode ? elem[ jQuery.expando ] : jQuery.expando;

	// If there is already no cache entry for this object, there is no
	// purpose in continuing
	if ( !cache[ id ] ) {
		return;
	}

	if ( name ) {

		thisCache = pvt ? cache[ id ] : cache[ id ].data;

		if ( thisCache ) {

			// Support array or space separated string names for data keys
			if ( !jQuery.isArray( name ) ) {

				// try the string as a key before any manipulation
				if ( name in thisCache ) {
					name = [ name ];
				} else {

					// split the camel cased version by spaces unless a key with the spaces exists
					name = jQuery.camelCase( name );
					if ( name in thisCache ) {
						name = [ name ];
					} else {
						name = name.split( " " );
					}
				}
			} else {

				// 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 = name.concat( jQuery.map( name, jQuery.camelCase ) );
			}

			i = name.length;
			while ( i-- ) {
				delete thisCache[ name[ i ] ];
			}

			// If there is no data left in the cache, we want to continue
			// and let the cache object itself get destroyed
			if ( pvt ? !isEmptyDataObject( thisCache ) : !jQuery.isEmptyObject( thisCache ) ) {
				return;
			}
		}
	}

	// See jQuery.data for more information
	if ( !pvt ) {
		delete cache[ id ].data;

		// Don't destroy the parent cache unless the internal data object
		// had been the only thing left in it
		if ( !isEmptyDataObject( cache[ id ] ) ) {
			return;
		}
	}

	// Destroy the cache
	if ( isNode ) {
		jQuery.cleanData( [ elem ], true );

	// Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
	/* jshint eqeqeq: false */
	} else if ( support.deleteExpando || cache != cache.window ) {
		/* jshint eqeqeq: true */
		delete cache[ id ];

	// When all else fails, undefined
	} else {
		cache[ id ] = undefined;
	}
}

jQuery.extend( {
	cache: {},

	// The following elements (space-suffixed to avoid Object.prototype collisions)
	// throw uncatchable exceptions if you attempt to set expando properties
	noData: {
		"applet ": true,
		"embed ": true,

		// ...but Flash objects (which have this classid) *can* handle expandos
		"object ": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
	},

	hasData: function( elem ) {
		elem = elem.nodeType ? jQuery.cache[ elem[ jQuery.expando ] ] : elem[ jQuery.expando ];
		return !!elem && !isEmptyDataObject( elem );
	},

	data: function( elem, name, data ) {
		return internalData( elem, name, data );
	},

	removeData: function( elem, name ) {
		return internalRemoveData( elem, name );
	},

	// For internal use only.
	_data: function( elem, name, data ) {
		return internalData( elem, name, data, true );
	},

	_removeData: function( elem, name ) {
		return internalRemoveData( elem, name, true );
	}
} );

jQuery.fn.extend( {
	data: function( key, value ) {
		var i, name, data,
			elem = this[ 0 ],
			attrs = elem && elem.attributes;

		// Special expections of .data basically thwart jQuery.access,
		// so implement the relevant behavior ourselves

		// Gets all values
		if ( key === undefined ) {
			if ( this.length ) {
				data = jQuery.data( elem );

				if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
					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 ] );
							}
						}
					}
					jQuery._data( elem, "parsedAttrs", true );
				}
			}

			return data;
		}

		// Sets multiple values
		if ( typeof key === "object" ) {
			return this.each( function() {
				jQuery.data( this, key );
			} );
		}

		return arguments.length > 1 ?

			// Sets one value
			this.each( function() {
				jQuery.data( this, key, value );
			} ) :

			// Gets one value
			// Try to fetch any internally stored data first
			elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : undefined;
	},

	removeData: function( key ) {
		return this.each( function() {
			jQuery.removeData( this, key );
		} );
	}
} );


jQuery.extend( {
	queue: function( elem, type, data ) {
		var queue;

		if ( elem ) {
			type = ( type || "fx" ) + "queue";
			queue = jQuery._data( elem, type );

			// Speed up dequeue by getting out quickly if this is just a lookup
			if ( data ) {
				if ( !queue || jQuery.isArray( data ) ) {
					queue = jQuery._data( 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 intended for public consumption - generates a queueHooks object,
	// or returns the current one
	_queueHooks: function( elem, type ) {
		var key = type + "queueHooks";
		return jQuery._data( elem, key ) || jQuery._data( elem, key, {
			empty: jQuery.Callbacks( "once memory" ).add( function() {
				jQuery._removeData( elem, type + "queue" );
				jQuery._removeData( elem, 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 = jQuery._data( elements[ i ], type + "queueHooks" );
			if ( tmp && tmp.empty ) {
				count++;
				tmp.empty.add( resolve );
			}
		}
		resolve();
		return defer.promise( obj );
	}
} );


( function() {
	var shrinkWrapBlocksVal;

	support.shrinkWrapBlocks = function() {
		if ( shrinkWrapBlocksVal != null ) {
			return shrinkWrapBlocksVal;
		}

		// Will be changed later if needed.
		shrinkWrapBlocksVal = false;

		// Minified: var b,c,d
		var div, body, container;

		body = document.getElementsByTagName( "body" )[ 0 ];
		if ( !body || !body.style ) {

			// Test fired too early or in an unsupported environment, exit.
			return;
		}

		// Setup
		div = document.createElement( "div" );
		container = document.createElement( "div" );
		container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px";
		body.appendChild( container ).appendChild( div );

		// Support: IE6
		// Check if elements with layout shrink-wrap their children
		if ( typeof div.style.zoom !== "undefined" ) {

			// Reset CSS: box-sizing; display; margin; border
			div.style.cssText =

				// Support: Firefox<29, Android 2.3
				// Vendor-prefix box-sizing
				"-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" +
				"box-sizing:content-box;display:block;margin:0;border:0;" +
				"padding:1px;width:1px;zoom:1";
			div.appendChild( document.createElement( "div" ) ).style.width = "5px";
			shrinkWrapBlocksVal = div.offsetWidth !== 3;
		}

		body.removeChild( container );

		return shrinkWrapBlocksVal;
	};

} )();
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;
}


// 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,
		length = 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 < length; i++ ) {
				fn(
					elems[ i ],
					key,
					raw ? value : value.call( elems[ i ], i, fn( elems[ i ], key ) )
				);
			}
		}
	}

	return chainable ?
		elems :

		// Gets
		bulk ?
			fn.call( elems ) :
			length ? fn( elems[ 0 ], key ) : emptyGet;
};
var rcheckableType = ( /^(?:checkbox|radio)$/i );

var rtagName = ( /<([\w:-]+)/ );

var rscriptType = ( /^$|\/(?:java|ecma)script/i );

var rleadingWhitespace = ( /^\s+/ );

var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|" +
		"details|dialog|figcaption|figure|footer|header|hgroup|main|" +
		"mark|meter|nav|output|picture|progress|section|summary|template|time|video";



function createSafeFragment( document ) {
	var list = nodeNames.split( "|" ),
		safeFrag = document.createDocumentFragment();

	if ( safeFrag.createElement ) {
		while ( list.length ) {
			safeFrag.createElement(
				list.pop()
			);
		}
	}
	return safeFrag;
}


( function() {
	var div = document.createElement( "div" ),
		fragment = document.createDocumentFragment(),
		input = document.createElement( "input" );

	// Setup
	div.innerHTML = "  <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";

	// IE strips leading whitespace when .innerHTML is used
	support.leadingWhitespace = div.firstChild.nodeType === 3;

	// Make sure that tbody elements aren't automatically inserted
	// IE will insert them into empty tables
	support.tbody = !div.getElementsByTagName( "tbody" ).length;

	// Make sure that link elements get serialized correctly by innerHTML
	// This requires a wrapper element in IE
	support.htmlSerialize = !!div.getElementsByTagName( "link" ).length;

	// Makes sure cloning an html5 element does not cause problems
	// Where outerHTML is undefined, this still works
	support.html5Clone =
		document.createElement( "nav" ).cloneNode( true ).outerHTML !== "<:nav></:nav>";

	// Check if a disconnected checkbox will retain its checked
	// value of true after appended to the DOM (IE6/7)
	input.type = "checkbox";
	input.checked = true;
	fragment.appendChild( input );
	support.appendChecked = input.checked;

	// Make sure textarea (and checkbox) defaultValue is properly cloned
	// Support: IE6-IE11+
	div.innerHTML = "<textarea>x</textarea>";
	support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;

	// #11217 - WebKit loses check when the name is after the checked attribute
	fragment.appendChild( div );

	// Support: Windows Web Apps (WWA)
	// `name` and `type` must use .setAttribute for WWA (#14901)
	input = document.createElement( "input" );
	input.setAttribute( "type", "radio" );
	input.setAttribute( "checked", "checked" );
	input.setAttribute( "name", "t" );

	div.appendChild( input );

	// Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3
	// old WebKit doesn't clone checked state correctly in fragments
	support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;

	// Support: IE<9
	// Cloned elements keep attachEvent handlers, we use addEventListener on IE9+
	support.noCloneEvent = !!div.addEventListener;

	// Support: IE<9
	// Since attributes and properties are the same in IE,
	// cleanData must set properties to undefined rather than use removeAttribute
	div[ jQuery.expando ] = 1;
	support.attributes = !div.getAttribute( jQuery.expando );
} )();


// We have to close these tags to support XHTML (#13200)
var wrapMap = {
	option: [ 1, "<select multiple='multiple'>", "</select>" ],
	legend: [ 1, "<fieldset>", "</fieldset>" ],
	area: [ 1, "<map>", "</map>" ],

	// Support: IE8
	param: [ 1, "<object>", "</object>" ],
	thead: [ 1, "<table>", "</table>" ],
	tr: [ 2, "<table><tbody>", "</tbody></table>" ],
	col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
	td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],

	// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
	// unless wrapped in a div with non-breaking characters in front of it.
	_default: support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ]
};

// Support: IE8-IE9
wrapMap.optgroup = wrapMap.option;

wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;


function getAll( context, tag ) {
	var elems, elem,
		i = 0,
		found = typeof context.getElementsByTagName !== "undefined" ?
			context.getElementsByTagName( tag || "*" ) :
			typeof context.querySelectorAll !== "undefined" ?
				context.querySelectorAll( tag || "*" ) :
				undefined;

	if ( !found ) {
		for ( found = [], elems = context.childNodes || context;
			( elem = elems[ i ] ) != null;
			i++
		) {
			if ( !tag || jQuery.nodeName( elem, tag ) ) {
				found.push( elem );
			} else {
				jQuery.merge( found, getAll( elem, tag ) );
			}
		}
	}

	return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
		jQuery.merge( [ context ], found ) :
		found;
}


// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
	var elem,
		i = 0;
	for ( ; ( elem = elems[ i ] ) != null; i++ ) {
		jQuery._data(
			elem,
			"globalEval",
			!refElements || jQuery._data( refElements[ i ], "globalEval" )
		);
	}
}


var rhtml = /<|&#?\w+;/,
	rtbody = /<tbody/i;

function fixDefaultChecked( elem ) {
	if ( rcheckableType.test( elem.type ) ) {
		elem.defaultChecked = elem.checked;
	}
}

function buildFragment( elems, context, scripts, selection, ignored ) {
	var j, elem, contains,
		tmp, tag, tbody, wrap,
		l = elems.length,

		// Ensure a safe fragment
		safe = createSafeFragment( context ),

		nodes = [],
		i = 0;

	for ( ; i < l; i++ ) {
		elem = elems[ i ];

		if ( elem || elem === 0 ) {

			// Add nodes directly
			if ( jQuery.type( elem ) === "object" ) {
				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 || safe.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;
				}

				// Manually add leading whitespace removed by IE
				if ( !support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
					nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[ 0 ] ) );
				}

				// Remove IE's autoinserted <tbody> from table fragments
				if ( !support.tbody ) {

					// String was a <table>, *may* have spurious <tbody>
					elem = tag === "table" && !rtbody.test( elem ) ?
						tmp.firstChild :

						// String was a bare <thead> or <tfoot>
						wrap[ 1 ] === "<table>" && !rtbody.test( elem ) ?
							tmp :
							0;

					j = elem && elem.childNodes.length;
					while ( j-- ) {
						if ( jQuery.nodeName( ( tbody = elem.childNodes[ j ] ), "tbody" ) &&
							!tbody.childNodes.length ) {

							elem.removeChild( tbody );
						}
					}
				}

				jQuery.merge( nodes, tmp.childNodes );

				// Fix #12392 for WebKit and IE > 9
				tmp.textContent = "";

				// Fix #12392 for oldIE
				while ( tmp.firstChild ) {
					tmp.removeChild( tmp.firstChild );
				}

				// Remember the top-level container for proper cleanup
				tmp = safe.lastChild;
			}
		}
	}

	// Fix #11356: Clear elements from fragment
	if ( tmp ) {
		safe.removeChild( tmp );
	}

	// Reset defaultChecked for any radios and checkboxes
	// about to be appended to the DOM in IE 6/7 (#8060)
	if ( !support.appendChecked ) {
		jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked );
	}

	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( safe.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 );
				}
			}
		}
	}

	tmp = null;

	return safe;
}


( function() {
	var i, eventName,
		div = document.createElement( "div" );

	// Support: IE<9 (lack submit/change bubble), Firefox (lack focus(in | out) events)
	for ( i in { submit: true, change: true, focusin: true } ) {
		eventName = "on" + i;

		if ( !( support[ i ] = eventName in window ) ) {

			// Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP)
			div.setAttribute( eventName, "t" );
			support[ i ] = div.attributes[ eventName ].expando === false;
		}
	}

	// Null elements to avoid leaks in IE.
	div = null;
} )();


var rformElems = /^(?:input|select|textarea)$/i,
	rkeyEvent = /^key/,
	rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/,
	rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
	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 tmp, events, t, handleObjIn,
			special, eventHandle, handleObj,
			handlers, type, namespaces, origType,
			elemData = jQuery._data( 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" &&
					( !e || jQuery.event.triggered !== e.type ) ?
					jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
					undefined;
			};

			// Add elem as a property of the handle fn to prevent a memory leak
			// with IE non-native events
			eventHandle.elem = elem;
		}

		// 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/attachEvent if the special events handler returns false
				if ( !special.setup ||
					special.setup.call( elem, data, namespaces, eventHandle ) === false ) {

					// Bind the global event handler to the element
					if ( elem.addEventListener ) {
						elem.addEventListener( type, eventHandle, false );

					} else if ( elem.attachEvent ) {
						elem.attachEvent( "on" + 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;
		}

		// Nullify elem to prevent memory leaks in IE
		elem = null;
	},

	// Detach an event or set of events from an element
	remove: function( elem, types, handler, selector, mappedTypes ) {
		var j, handleObj, tmp,
			origCount, t, events,
			special, handlers, type,
			namespaces, origType,
			elemData = jQuery.hasData( elem ) && jQuery._data( 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 the expando if it's no longer used
		if ( jQuery.isEmptyObject( events ) ) {
			delete elemData.handle;

			// removeData also checks for emptiness and clears the expando if empty
			// so use it instead of delete
			jQuery._removeData( elem, "events" );
		}
	},

	trigger: function( event, data, elem, onlyHandlers ) {
		var handle, ontype, cur,
			bubbleType, special, tmp, i,
			eventPath = [ elem || document ],
			type = hasOwn.call( event, "type" ) ? event.type : event,
			namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : [];

		cur = tmp = elem = elem || document;

		// Don't do events on text and comment nodes
		if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
			return;
		}

		// focus/blur morphs to focusin/out; ensure we're not firing them right now
		if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
			return;
		}

		if ( type.indexOf( "." ) > -1 ) {

			// Namespaced trigger; create a regexp to match event type in handle()
			namespaces = type.split( "." );
			type = namespaces.shift();
			namespaces.sort();
		}
		ontype = type.indexOf( ":" ) < 0 && "on" + type;

		// Caller can pass in a jQuery.Event object, Object, or just an event type string
		event = event[ jQuery.expando ] ?
			event :
			new jQuery.Event( type, typeof event === "object" && event );

		// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
		event.isTrigger = onlyHandlers ? 2 : 3;
		event.namespace = namespaces.join( "." );
		event.rnamespace = event.namespace ?
			new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) :
			null;

		// Clean up the event in case it is being reused
		event.result = undefined;
		if ( !event.target ) {
			event.target = elem;
		}

		// Clone any incoming data and prepend the event, creating the handler arg list
		data = data == null ?
			[ event ] :
			jQuery.makeArray( data, [ event ] );

		// Allow special events to draw outside the lines
		special = jQuery.event.special[ type ] || {};
		if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
			return;
		}

		// Determine event propagation path in advance, per W3C events spec (#9951)
		// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
		if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {

			bubbleType = special.delegateType || type;
			if ( !rfocusMorph.test( bubbleType + type ) ) {
				cur = cur.parentNode;
			}
			for ( ; cur; cur = cur.parentNode ) {
				eventPath.push( cur );
				tmp = cur;
			}

			// Only add window if we got to document (e.g., not plain obj or detached DOM)
			if ( tmp === ( elem.ownerDocument || document ) ) {
				eventPath.push( tmp.defaultView || tmp.parentWindow || window );
			}
		}

		// Fire handlers on the event path
		i = 0;
		while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) {

			event.type = i > 1 ?
				bubbleType :
				special.bindType || type;

			// jQuery handler
			handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] &&
				jQuery._data( cur, "handle" );

			if ( handle ) {
				handle.apply( cur, data );
			}

			// Native handler
			handle = ontype && cur[ ontype ];
			if ( handle && handle.apply && acceptData( cur ) ) {
				event.result = handle.apply( cur, data );
				if ( event.result === false ) {
					event.preventDefault();
				}
			}
		}
		event.type = type;

		// If nobody prevented the default action, do it now
		if ( !onlyHandlers && !event.isDefaultPrevented() ) {

			if (
				( !special._default ||
				 special._default.apply( eventPath.pop(), data ) === false
				) && acceptData( elem )
			) {

				// Call a native DOM method on the target with the same name name as the event.
				// Can't use an .isFunction() check here because IE6/7 fails that test.
				// Don't do default actions on window, that's where global variables be (#6170)
				if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) {

					// Don't re-trigger an onFOO event when we call its FOO() method
					tmp = elem[ ontype ];

					if ( tmp ) {
						elem[ ontype ] = null;
					}

					// Prevent re-triggering of the same event, since we already bubbled it above
					jQuery.event.triggered = type;
					try {
						elem[ type ]();
					} catch ( e ) {

						// IE<9 dies on focus/blur to hidden element (#1486,#12518)
						// only reproducible on winXP IE8 native, not IE9 in IE8 mode
					}
					jQuery.event.triggered = undefined;

					if ( tmp ) {
						elem[ ontype ] = tmp;
					}
				}
			}
		}

		return event.result;
	},

	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 = ( jQuery._data( 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 <use> instance trees (#13180)
		//
		// Support: Firefox<=42+
		// Avoid non-left-click in FF but don't block IE radio events (#3861, gh-2343)
		if ( delegateCount && cur.nodeType &&
			( event.type !== "click" || isNaN( event.button ) || event.button < 1 ) ) {

			/* jshint eqeqeq: false */
			for ( ; cur != this; cur = cur.parentNode || this ) {
				/* jshint eqeqeq: true */

				// Don't check non-elements (#13208)
				// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
				if ( cur.nodeType === 1 && ( cur.disabled !== true || event.type !== "click" ) ) {
					matches = [];
					for ( i = 0; i < delegateCount; i++ ) {
						handleObj = handlers[ i ];

						// Don't conflict with Object.prototype properties (#13203)
						sel = handleObj.selector + " ";

						if ( matches[ sel ] === undefined ) {
							matches[ sel ] = handleObj.needsContext ?
								jQuery( sel, this ).index( cur ) > -1 :
								jQuery.find( sel, this, null, [ cur ] ).length;
						}
						if ( matches[ sel ] ) {
							matches.push( handleObj );
						}
					}
					if ( matches.length ) {
						handlerQueue.push( { elem: cur, handlers: matches } );
					}
				}
			}
		}

		// Add the remaining (directly-bound) handlers
		if ( delegateCount < handlers.length ) {
			handlerQueue.push( { elem: this, handlers: handlers.slice( delegateCount ) } );
		}

		return handlerQueue;
	},

	fix: function( event ) {
		if ( event[ jQuery.expando ] ) {
			return event;
		}

		// Create a writable copy of the event object and normalize some properties
		var i, prop, copy,
			type = event.type,
			originalEvent = event,
			fixHook = this.fixHooks[ type ];

		if ( !fixHook ) {
			this.fixHooks[ type ] = fixHook =
				rmouseEvent.test( type ) ? this.mouseHooks :
				rkeyEvent.test( type ) ? this.keyHooks :
				{};
		}
		copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;

		event = new jQuery.Event( originalEvent );

		i = copy.length;
		while ( i-- ) {
			prop = copy[ i ];
			event[ prop ] = originalEvent[ prop ];
		}

		// Support: IE<9
		// Fix target property (#1925)
		if ( !event.target ) {
			event.target = originalEvent.srcElement || document;
		}

		// Support: Safari 6-8+
		// Target should not be a text node (#504, #13143)
		if ( event.target.nodeType === 3 ) {
			event.target = event.target.parentNode;
		}

		// Support: IE<9
		// For mouse/key events, metaKey==false if it's undefined (#3368, #11328)
		event.metaKey = !!event.metaKey;

		return fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
	},

	// Includes some event props shared by KeyEvent and MouseEvent
	props: ( "altKey bubbles cancelable ctrlKey currentTarget detail eventPhase " +
		"metaKey relatedTarget shiftKey target timeStamp view which" ).split( " " ),

	fixHooks: {},

	keyHooks: {
		props: "char charCode key keyCode".split( " " ),
		filter: function( event, original ) {

			// Add which for key events
			if ( event.which == null ) {
				event.which = original.charCode != null ? original.charCode : original.keyCode;
			}

			return event;
		}
	},

	mouseHooks: {
		props: ( "button buttons clientX clientY fromElement offsetX offsetY " +
			"pageX pageY screenX screenY toElement" ).split( " " ),
		filter: function( event, original ) {
			var body, eventDoc, doc,
				button = original.button,
				fromElement = original.fromElement;

			// Calculate pageX/Y if missing and clientX/Y available
			if ( event.pageX == null && original.clientX != null ) {
				eventDoc = event.target.ownerDocument || document;
				doc = eventDoc.documentElement;
				body = eventDoc.body;

				event.pageX = original.clientX +
					( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) -
					( doc && doc.clientLeft || body && body.clientLeft || 0 );
				event.pageY = original.clientY +
					( doc && doc.scrollTop  || body && body.scrollTop  || 0 ) -
					( doc && doc.clientTop  || body && body.clientTop  || 0 );
			}

			// Add relatedTarget, if necessary
			if ( !event.relatedTarget && fromElement ) {
				event.relatedTarget = fromElement === event.target ?
					original.toElement :
					fromElement;
			}

			// Add which for click: 1 === left; 2 === middle; 3 === right
			// Note: button is not normalized, so don't use it
			if ( !event.which && button !== undefined ) {
				event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
			}

			return event;
		}
	},

	special: {
		load: {

			// Prevent triggered image.load events from bubbling to window.load
			noBubble: true
		},
		focus: {

			// Fire native event if possible so blur/focus sequence is correct
			trigger: function() {
				if ( this !== safeActiveElement() && this.focus ) {
					try {
						this.focus();
						return false;
					} catch ( e ) {

						// Support: IE<9
						// If we error on focus to hidden element (#1486, #12518),
						// let .trigger() run the handlers
					}
				}
			},
			delegateType: "focusin"
		},
		blur: {
			trigger: function() {
				if ( this === safeActiveElement() && this.blur ) {
					this.blur();
					return false;
				}
			},
			delegateType: "focusout"
		},
		click: {

			// For checkbox, fire native event so checked state will be right
			trigger: function() {
				if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) {
					this.click();
					return false;
				}
			},

			// For cross-browser consistency, don't fire native .click() on links
			_default: function( event ) {
				return jQuery.nodeName( event.target, "a" );
			}
		},

		beforeunload: {
			postDispatch: function( event ) {

				// Support: Firefox 20+
				// Firefox doesn't alert if the returnValue field is not set.
				if ( event.result !== undefined && event.originalEvent ) {
					event.originalEvent.returnValue = event.result;
				}
			}
		}
	},

	// Piggyback on a donor event to simulate a different one
	simulate: function( type, elem, event ) {
		var e = jQuery.extend(
			new jQuery.Event(),
			event,
			{
				type: type,
				isSimulated: true

				// Previously, `originalEvent: {}` was set here, so stopPropagation call
				// would not be triggered on donor event, since in our own
				// jQuery.event.stopPropagation function we had a check for existence of
				// originalEvent.stopPropagation method, so, consequently it would be a noop.
				//
				// Guard for simulated events was moved to jQuery.event.stopPropagation function
				// since `originalEvent` should point to the original event for the
				// constancy with other events and for more focused logic
			}
		);

		jQuery.event.trigger( e, null, elem );

		if ( e.isDefaultPrevented() ) {
			event.preventDefault();
		}
	}
};

jQuery.removeEvent = document.removeEventListener ?
	function( elem, type, handle ) {

		// This "if" is needed for plain objects
		if ( elem.removeEventListener ) {
			elem.removeEventListener( type, handle );
		}
	} :
	function( elem, type, handle ) {
		var name = "on" + type;

		if ( elem.detachEvent ) {

			// #8545, #7054, preventing memory leaks for custom events in IE6-8
			// detachEvent needed property on element, by name of that event,
			// to properly expose it to GC
			if ( typeof elem[ name ] === "undefined" ) {
				elem[ name ] = null;
			}

			elem.detachEvent( name, handle );
		}
	};

jQuery.Event = function( src, props ) {

	// Allow instantiation without the 'new' keyword
	if ( !( this instanceof jQuery.Event ) ) {
		return new jQuery.Event( src, props );
	}

	// Event object
	if ( src && src.type ) {
		this.originalEvent = src;
		this.type = src.type;

		// Events bubbling up the document may have been marked as prevented
		// by a handler lower down the tree; reflect the correct value.
		this.isDefaultPrevented = src.defaultPrevented ||
				src.defaultPrevented === undefined &&

				// Support: IE < 9, Android < 4.0
				src.returnValue === false ?
			returnTrue :
			returnFalse;

	// Event type
	} else {
		this.type = src;
	}

	// Put explicitly provided properties onto the event object
	if ( props ) {
		jQuery.extend( this, props );
	}

	// Create a timestamp if incoming event doesn't have one
	this.timeStamp = src && src.timeStamp || jQuery.now();

	// Mark it as fixed
	this[ jQuery.expando ] = true;
};

// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
	constructor: jQuery.Event,
	isDefaultPrevented: returnFalse,
	isPropagationStopped: returnFalse,
	isImmediatePropagationStopped: returnFalse,

	preventDefault: function() {
		var e = this.originalEvent;

		this.isDefaultPrevented = returnTrue;
		if ( !e ) {
			return;
		}

		// If preventDefault exists, run it on the original event
		if ( e.preventDefault ) {
			e.preventDefault();

		// Support: IE
		// Otherwise set the returnValue property of the original event to false
		} else {
			e.returnValue = false;
		}
	},
	stopPropagation: function() {
		var e = this.originalEvent;

		this.isPropagationStopped = returnTrue;

		if ( !e || this.isSimulated ) {
			return;
		}

		// If stopPropagation exists, run it on the original event
		if ( e.stopPropagation ) {
			e.stopPropagation();
		}

		// Support: IE
		// Set the cancelBubble property of the original event to true
		e.cancelBubble = true;
	},
	stopImmediatePropagation: function() {
		var e = this.originalEvent;

		this.isImmediatePropagationStopped = returnTrue;

		if ( e && e.stopImmediatePropagation ) {
			e.stopImmediatePropagation();
		}

		this.stopPropagation();
	}
};

// Create mouseenter/leave events using mouseover/out and event-time checks
// so that event delegation works in jQuery.
// Do the same for pointerenter/pointerleave and pointerover/pointerout
//
// Support: Safari 7 only
// Safari sends mouseenter too often; see:
// https://code.google.com/p/chromium/issues/detail?id=470258
// for the description of the bug (it existed in older Chrome versions as well).
jQuery.each( {
	mouseenter: "mouseover",
	mouseleave: "mouseout",
	pointerenter: "pointerover",
	pointerleave: "pointerout"
}, function( orig, fix ) {
	jQuery.event.special[ orig ] = {
		delegateType: fix,
		bindType: fix,

		handle: function( event ) {
			var ret,
				target = this,
				related = event.relatedTarget,
				handleObj = event.handleObj;

			// For mouseenter/leave call the handler if related is outside the target.
			// NB: No relatedTarget if the mouse left/entered the browser window
			if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) {
				event.type = handleObj.origType;
				ret = handleObj.handler.apply( this, arguments );
				event.type = fix;
			}
			return ret;
		}
	};
} );

// IE submit delegation
if ( !support.submit ) {

	jQuery.event.special.submit = {
		setup: function() {

			// Only need this for delegated form submit events
			if ( jQuery.nodeName( this, "form" ) ) {
				return false;
			}

			// Lazy-add a submit handler when a descendant form may potentially be submitted
			jQuery.event.add( this, "click._submit keypress._submit", function( e ) {

				// Node name check avoids a VML-related crash in IE (#9807)
				var elem = e.target,
					form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ?

						// Support: IE <=8
						// We use jQuery.prop instead of elem.form
						// to allow fixing the IE8 delegated submit issue (gh-2332)
						// by 3rd party polyfills/workarounds.
						jQuery.prop( elem, "form" ) :
						undefined;

				if ( form && !jQuery._data( form, "submit" ) ) {
					jQuery.event.add( form, "submit._submit", function( event ) {
						event._submitBubble = true;
					} );
					jQuery._data( form, "submit", true );
				}
			} );

			// return undefined since we don't need an event listener
		},

		postDispatch: function( event ) {

			// If form was submitted by the user, bubble the event up the tree
			if ( event._submitBubble ) {
				delete event._submitBubble;
				if ( this.parentNode && !event.isTrigger ) {
					jQuery.event.simulate( "submit", this.parentNode, event );
				}
			}
		},

		teardown: function() {

			// Only need this for delegated form submit events
			if ( jQuery.nodeName( this, "form" ) ) {
				return false;
			}

			// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
			jQuery.event.remove( this, "._submit" );
		}
	};
}

// IE change delegation and checkbox/radio fix
if ( !support.change ) {

	jQuery.event.special.change = {

		setup: function() {

			if ( rformElems.test( this.nodeName ) ) {

				// IE doesn't fire change on a check/radio until blur; trigger it on click
				// after a propertychange. Eat the blur-change in special.change.handle.
				// This still fires onchange a second time for check/radio after blur.
				if ( this.type === "checkbox" || this.type === "radio" ) {
					jQuery.event.add( this, "propertychange._change", function( event ) {
						if ( event.originalEvent.propertyName === "checked" ) {
							this._justChanged = true;
						}
					} );
					jQuery.event.add( this, "click._change", function( event ) {
						if ( this._justChanged && !event.isTrigger ) {
							this._justChanged = false;
						}

						// Allow triggered, simulated change events (#11500)
						jQuery.event.simulate( "change", this, event );
					} );
				}
				return false;
			}

			// Delegated event; lazy-add a change handler on descendant inputs
			jQuery.event.add( this, "beforeactivate._change", function( e ) {
				var elem = e.target;

				if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "change" ) ) {
					jQuery.event.add( elem, "change._change", function( event ) {
						if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
							jQuery.event.simulate( "change", this.parentNode, event );
						}
					} );
					jQuery._data( elem, "change", true );
				}
			} );
		},

		handle: function( event ) {
			var elem = event.target;

			// Swallow native change events from checkbox/radio, we already triggered them above
			if ( this !== elem || event.isSimulated || event.isTrigger ||
				( elem.type !== "radio" && elem.type !== "checkbox" ) ) {

				return event.handleObj.handler.apply( this, arguments );
			}
		},

		teardown: function() {
			jQuery.event.remove( this, "._change" );

			return !rformElems.test( this.nodeName );
		}
	};
}

// Support: Firefox
// Firefox doesn't have focus(in | out) events
// Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787
//
// Support: Chrome, Safari
// focus(in | out) events fire after focus & blur events,
// which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order
// Related ticket - https://code.google.com/p/chromium/issues/detail?id=449857
if ( !support.focusin ) {
	jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) {

		// Attach a single capturing handler on the document while someone wants focusin/focusout
		var handler = function( event ) {
			jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) );
		};

		jQuery.event.special[ fix ] = {
			setup: function() {
				var doc = this.ownerDocument || this,
					attaches = jQuery._data( doc, fix );

				if ( !attaches ) {
					doc.addEventListener( orig, handler, true );
				}
				jQuery._data( doc, fix, ( attaches || 0 ) + 1 );
			},
			teardown: function() {
				var doc = this.ownerDocument || this,
					attaches = jQuery._data( doc, fix ) - 1;

				if ( !attaches ) {
					doc.removeEventListener( orig, handler, true );
					jQuery._removeData( doc, fix );
				} else {
					jQuery._data( doc, fix, attaches );
				}
			}
		};
	} );
}

jQuery.fn.extend( {

	on: function( types, selector, data, fn ) {
		return on( this, types, selector, data, fn );
	},
	one: function( types, selector, data, fn ) {
		return on( this, types, selector, data, fn, 1 );
	},
	off: function( types, selector, fn ) {
		var handleObj, type;
		if ( types && types.preventDefault && types.handleObj ) {

			// ( event )  dispatched jQuery.Event
			handleObj = types.handleObj;
			jQuery( types.delegateTarget ).off(
				handleObj.namespace ?
					handleObj.origType + "." + handleObj.namespace :
					handleObj.origType,
				handleObj.selector,
				handleObj.handler
			);
			return this;
		}
		if ( typeof types === "object" ) {

			// ( types-object [, selector] )
			for ( type in types ) {
				this.off( type, selector, types[ type ] );
			}
			return this;
		}
		if ( selector === false || typeof selector === "function" ) {

			// ( types [, fn] )
			fn = selector;
			selector = undefined;
		}
		if ( fn === false ) {
			fn = returnFalse;
		}
		return this.each( function() {
			jQuery.event.remove( this, types, fn, selector );
		} );
	},

	trigger: function( type, data ) {
		return this.each( function() {
			jQuery.event.trigger( type, data, this );
		} );
	},
	triggerHandler: function( type, data ) {
		var elem = this[ 0 ];
		if ( elem ) {
			return jQuery.event.trigger( type, data, elem, true );
		}
	}
} );


var rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
	rnoshimcache = new RegExp( "<(?:" + nodeNames + ")[\\s/>]", "i" ),
	rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi,

	// Support: IE 10-11, Edge 10240+
	// In IE/Edge using regex groups here causes severe slowdowns.
	// See https://connect.microsoft.com/IE/feedback/details/1736512/
	rnoInnerhtml = /<script|<style|<link/i,

	// checked="checked" or checked
	rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
	rscriptTypeMasked = /^true\/(.*)/,
	rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
	safeFragment = createSafeFragment( document ),
	fragmentDiv = safeFragment.appendChild( document.createElement( "div" ) );

// Support: IE<8
// Manipulating tables requires a tbody
function manipulationTarget( elem, content ) {
	return jQuery.nodeName( elem, "table" ) &&
		jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ?

		elem.getElementsByTagName( "tbody" )[ 0 ] ||
			elem.appendChild( elem.ownerDocument.createElement( "tbody" ) ) :
		elem;
}

// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
	elem.type = ( jQuery.find.attr( elem, "type" ) !== null ) + "/" + elem.type;
	return elem;
}
function restoreScript( elem ) {
	var match = rscriptTypeMasked.exec( elem.type );
	if ( match ) {
		elem.type = match[ 1 ];
	} else {
		elem.removeAttribute( "type" );
	}
	return elem;
}

function cloneCopyEvent( src, dest ) {
	if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
		return;
	}

	var type, i, l,
		oldData = jQuery._data( src ),
		curData = jQuery._data( dest, oldData ),
		events = oldData.events;

	if ( events ) {
		delete curData.handle;
		curData.events = {};

		for ( type in events ) {
			for ( i = 0, l = events[ type ].length; i < l; i++ ) {
				jQuery.event.add( dest, type, events[ type ][ i ] );
			}
		}
	}

	// make the cloned public data object a copy from the original
	if ( curData.data ) {
		curData.data = jQuery.extend( {}, curData.data );
	}
}

function fixCloneNodeIssues( src, dest ) {
	var nodeName, e, data;

	// We do not need to do anything for non-Elements
	if ( dest.nodeType !== 1 ) {
		return;
	}

	nodeName = dest.nodeName.toLowerCase();

	// IE6-8 copies events bound via attachEvent when using cloneNode.
	if ( !support.noCloneEvent && dest[ jQuery.expando ] ) {
		data = jQuery._data( dest );

		for ( e in data.events ) {
			jQuery.removeEvent( dest, e, data.handle );
		}

		// Event data gets referenced instead of copied if the expando gets copied too
		dest.removeAttribute( jQuery.expando );
	}

	// IE blanks contents when cloning scripts, and tries to evaluate newly-set text
	if ( nodeName === "script" && dest.text !== src.text ) {
		disableScript( dest ).text = src.text;
		restoreScript( dest );

	// IE6-10 improperly clones children of object elements using classid.
	// IE10 throws NoModificationAllowedError if parent is null, #12132.
	} else if ( nodeName === "object" ) {
		if ( dest.parentNode ) {
			dest.outerHTML = src.outerHTML;
		}

		// This path appears unavoidable for IE9. When cloning an object
		// element in IE9, the outerHTML strategy above is not sufficient.
		// If the src has innerHTML and the destination does not,
		// copy the src.innerHTML into the dest.innerHTML. #10324
		if ( support.html5Clone && ( src.innerHTML && !jQuery.trim( dest.innerHTML ) ) ) {
			dest.innerHTML = src.innerHTML;
		}

	} else if ( nodeName === "input" && rcheckableType.test( src.type ) ) {

		// IE6-8 fails to persist the checked state of a cloned checkbox
		// or radio button. Worse, IE6-7 fail to give the cloned element
		// a checked appearance if the defaultChecked value isn't also set

		dest.defaultChecked = dest.checked = src.checked;

		// IE6-7 get confused and end up setting the value of a cloned
		// checkbox/radio button to an empty string instead of "on"
		if ( dest.value !== src.value ) {
			dest.value = src.value;
		}

	// IE6-8 fails to return the selected option to the default selected
	// state when cloning options
	} else if ( nodeName === "option" ) {
		dest.defaultSelected = dest.selected = src.defaultSelected;

	// IE6-8 fails to set the defaultValue to the correct value when
	// cloning other types of input fields
	} else if ( nodeName === "input" || nodeName === "textarea" ) {
		dest.defaultValue = src.defaultValue;
	}
}

function domManip( collection, args, callback, ignored ) {

	// Flatten any nested arrays
	args = concat.apply( [], args );

	var first, node, hasScripts,
		scripts, doc, fragment,
		i = 0,
		l = collection.length,
		iNoClone = l - 1,
		value = args[ 0 ],
		isFunction = jQuery.isFunction( value );

	// We can't cloneNode fragments that contain checked, in WebKit
	if ( isFunction ||
			( l > 1 && typeof value === "string" &&
				!support.checkClone && rchecked.test( value ) ) ) {
		return collection.each( function( index ) {
			var self = collection.eq( index );
			if ( isFunction ) {
				args[ 0 ] = value.call( this, index, self.html() );
			}
			domManip( self, args, callback, ignored );
		} );
	}

	if ( l ) {
		fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored );
		first = fragment.firstChild;

		if ( fragment.childNodes.length === 1 ) {
			fragment = first;
		}

		// Require either new content or an interest in ignored elements to invoke the callback
		if ( first || ignored ) {
			scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
			hasScripts = scripts.length;

			// Use the original fragment for the last item
			// instead of the first because it can end up
			// being emptied incorrectly in certain situations (#8070).
			for ( ; i < l; i++ ) {
				node = fragment;

				if ( i !== iNoClone ) {
					node = jQuery.clone( node, true, true );

					// Keep references to cloned scripts for later restoration
					if ( hasScripts ) {

						// Support: Android<4.1, PhantomJS<2
						// push.apply(_, arraylike) throws on ancient WebKit
						jQuery.merge( scripts, getAll( node, "script" ) );
					}
				}

				callback.call( collection[ i ], node, i );
			}

			if ( hasScripts ) {
				doc = scripts[ scripts.length - 1 ].ownerDocument;

				// Reenable scripts
				jQuery.map( scripts, restoreScript );

				// Evaluate executable scripts on first document insertion
				for ( i = 0; i < hasScripts; i++ ) {
					node = scripts[ i ];
					if ( rscriptType.test( node.type || "" ) &&
						!jQuery._data( node, "globalEval" ) &&
						jQuery.contains( doc, node ) ) {

						if ( node.src ) {

							// Optional AJAX dependency, but won't run scripts if not present
							if ( jQuery._evalUrl ) {
								jQuery._evalUrl( node.src );
							}
						} else {
							jQuery.globalEval(
								( node.text || node.textContent || node.innerHTML || "" )
									.replace( rcleanScript, "" )
							);
						}
					}
				}
			}

			// Fix #11809: Avoid leaking memory
			fragment = first = null;
		}
	}

	return collection;
}

function remove( elem, selector, keepData ) {
	var node,
		elems = selector ? jQuery.filter( selector, elem ) : elem,
		i = 0;

	for ( ; ( node = elems[ i ] ) != null; i++ ) {

		if ( !keepData && node.nodeType === 1 ) {
			jQuery.cleanData( getAll( node ) );
		}

		if ( node.parentNode ) {
			if ( keepData && jQuery.contains( node.ownerDocument, node ) ) {
				setGlobalEval( getAll( node, "script" ) );
			}
			node.parentNode.removeChild( node );
		}
	}

	return elem;
}

jQuery.extend( {
	htmlPrefilter: function( html ) {
		return html.replace( rxhtmlTag, "<$1></$2>" );
	},

	clone: function( elem, dataAndEvents, deepDataAndEvents ) {
		var destElements, node, clone, i, srcElements,
			inPage = jQuery.contains( elem.ownerDocument, elem );

		if ( support.html5Clone || jQuery.isXMLDoc( elem ) ||
			!rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {

			clone = elem.cloneNode( true );

		// IE<=8 does not properly clone detached, unknown element nodes
		} else {
			fragmentDiv.innerHTML = elem.outerHTML;
			fragmentDiv.removeChild( clone = fragmentDiv.firstChild );
		}

		if ( ( !support.noCloneEvent || !support.noCloneChecked ) &&
				( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) {

			// We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
			destElements = getAll( clone );
			srcElements = getAll( elem );

			// Fix all IE cloning issues
			for ( i = 0; ( node = srcElements[ i ] ) != null; ++i ) {

				// Ensure that the destination node is not null; Fixes #9587
				if ( destElements[ i ] ) {
					fixCloneNodeIssues( node, destElements[ i ] );
				}
			}
		}

		// Copy the events from the original to the clone
		if ( dataAndEvents ) {
			if ( deepDataAndEvents ) {
				srcElements = srcElements || getAll( elem );
				destElements = destElements || getAll( clone );

				for ( i = 0; ( node = srcElements[ i ] ) != null; i++ ) {
					cloneCopyEvent( node, destElements[ i ] );
				}
			} else {
				cloneCopyEvent( elem, clone );
			}
		}

		// Preserve script evaluation history
		destElements = getAll( clone, "script" );
		if ( destElements.length > 0 ) {
			setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
		}

		destElements = srcElements = node = null;

		// Return the cloned set
		return clone;
	},

	cleanData: function( elems, /* internal */ forceAcceptData ) {
		var elem, type, id, data,
			i = 0,
			internalKey = jQuery.expando,
			cache = jQuery.cache,
			attributes = support.attributes,
			special = jQuery.event.special;

		for ( ; ( elem = elems[ i ] ) != null; i++ ) {
			if ( forceAcceptData || acceptData( elem ) ) {

				id = elem[ internalKey ];
				data = id && cache[ id ];

				if ( data ) {
					if ( data.events ) {
						for ( type in data.events ) {
							if ( special[ type ] ) {
								jQuery.event.remove( elem, type );

							// This is a shortcut to avoid jQuery.event.remove's overhead
							} else {
								jQuery.removeEvent( elem, type, data.handle );
							}
						}
					}

					// Remove cache only if it was not already removed by jQuery.event.remove
					if ( cache[ id ] ) {

						delete cache[ id ];

						// Support: IE<9
						// IE does not allow us to delete expando properties from nodes
						// IE creates expando attributes along with the property
						// IE does not have a removeAttribute function on Document nodes
						if ( !attributes && typeof elem.removeAttribute !== "undefined" ) {
							elem.removeAttribute( internalKey );

						// 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
						} else {
							elem[ internalKey ] = undefined;
						}

						deletedIds.push( id );
					}
				}
			}
		}
	}
} );

jQuery.fn.extend( {

	// Keep domManip exposed until 3.0 (gh-2225)
	domManip: domManip,

	detach: function( selector ) {
		return remove( this, selector, true );
	},

	remove: function( selector ) {
		return remove( this, selector );
	},

	text: function( value ) {
		return access( this, function( value ) {
			return value === undefined ?
				jQuery.text( this ) :
				this.empty().append(
					( this[ 0 ] && this[ 0 ].ownerDocument || document ).createTextNode( value )
				);
		}, null, value, arguments.length );
	},

	append: function() {
		return domManip( this, arguments, function( elem ) {
			if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
				var target = manipulationTarget( this, elem );
				target.appendChild( elem );
			}
		} );
	},

	prepend: function() {
		return domManip( this, arguments, function( elem ) {
			if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
				var target = manipulationTarget( this, elem );
				target.insertBefore( elem, target.firstChild );
			}
		} );
	},

	before: function() {
		return domManip( this, arguments, function( elem ) {
			if ( this.parentNode ) {
				this.parentNode.insertBefore( elem, this );
			}
		} );
	},

	after: function() {
		return domManip( this, arguments, function( elem ) {
			if ( this.parentNode ) {
				this.parentNode.insertBefore( elem, this.nextSibling );
			}
		} );
	},

	empty: function() {
		var elem,
			i = 0;

		for ( ; ( elem = this[ i ] ) != null; i++ ) {

			// Remove element nodes and prevent memory leaks
			if ( elem.nodeType === 1 ) {
				jQuery.cleanData( getAll( elem, false ) );
			}

			// Remove any remaining nodes
			while ( elem.firstChild ) {
				elem.removeChild( elem.firstChild );
			}

			// If this is a select, ensure that it displays empty (#12336)
			// Support: IE<9
			if ( elem.options && jQuery.nodeName( elem, "select" ) ) {
				elem.options.length = 0;
			}
		}

		return this;
	},

	clone: function( dataAndEvents, deepDataAndEvents ) {
		dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
		deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;

		return this.map( function() {
			return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
		} );
	},

	html: function( value ) {
		return access( this, function( value ) {
			var elem = this[ 0 ] || {},
				i = 0,
				l = this.length;

			if ( value === undefined ) {
				return elem.nodeType === 1 ?
					elem.innerHTML.replace( rinlinejQuery, "" ) :
					undefined;
			}

			// See if we can take a shortcut and just use innerHTML
			if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
				( support.htmlSerialize || !rnoshimcache.test( value )  ) &&
				( support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
				!wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {

				value = jQuery.htmlPrefilter( value );

				try {
					for ( ; i < l; i++ ) {

						// Remove element nodes and prevent memory leaks
						elem = this[ i ] || {};
						if ( elem.nodeType === 1 ) {
							jQuery.cleanData( getAll( elem, false ) );
							elem.innerHTML = value;
						}
					}

					elem = 0;

				// If using innerHTML throws an exception, use the fallback method
				} catch ( e ) {}
			}

			if ( elem ) {
				this.empty().append( value );
			}
		}, null, value, arguments.length );
	},

	replaceWith: function() {
		var ignored = [];

		// Make the changes, replacing each non-ignored context element with the new content
		return domManip( this, arguments, function( elem ) {
			var parent = this.parentNode;

			if ( jQuery.inArray( this, ignored ) < 0 ) {
				jQuery.cleanData( getAll( this ) );
				if ( parent ) {
					parent.replaceChild( elem, this );
				}
			}

		// Force callback invocation
		}, ignored );
	}
} );

jQuery.each( {
	appendTo: "append",
	prependTo: "prepend",
	insertBefore: "before",
	insertAfter: "after",
	replaceAll: "replaceWith"
}, function( name, original ) {
	jQuery.fn[ name ] = function( selector ) {
		var elems,
			i = 0,
			ret = [],
			insert = jQuery( selector ),
			last = insert.length - 1;

		for ( ; i <= last; i++ ) {
			elems = i === last ? this : this.clone( true );
			jQuery( insert[ i ] )[ original ]( elems );

			// Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get()
			push.apply( ret, elems.get() );
		}

		return this.pushStack( ret );
	};
} );


var iframe,
	elemdisplay = {

		// Support: Firefox
		// We have to pre-define these values for FF (#10227)
		HTML: "block",
		BODY: "block"
	};

/**
 * Retrieve the actual display of a element
 * @param {String} name nodeName of the element
 * @param {Object} doc Document object
 */

// Called only from within defaultDisplay
function actualDisplay( name, doc ) {
	var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),

		display = jQuery.css( elem[ 0 ], "display" );

	// We don't have any data stored on the element,
	// so use "detach" method as fast way to get rid of the element
	elem.detach();

	return display;
}

/**
 * Try to determine the default display value of an element
 * @param {String} nodeName
 */
function defaultDisplay( nodeName ) {
	var doc = document,
		display = elemdisplay[ nodeName ];

	if ( !display ) {
		display = actualDisplay( nodeName, doc );

		// If the simple way fails, read from inside an iframe
		if ( display === "none" || !display ) {

			// Use the already-created iframe if possible
			iframe = ( iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" ) )
				.appendTo( doc.documentElement );

			// Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
			doc = ( iframe[ 0 ].contentWindow || iframe[ 0 ].contentDocument ).document;

			// Support: IE
			doc.write();
			doc.close();

			display = actualDisplay( nodeName, doc );
			iframe.detach();
		}

		// Store the correct default display
		elemdisplay[ nodeName ] = display;
	}

	return display;
}
var rmargin = ( /^margin/ );

var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );

var swap = function( elem, options, callback, args ) {
	var ret, name,
		old = {};

	// Remember the old values, and insert the new ones
	for ( name in options ) {
		old[ name ] = elem.style[ name ];
		elem.style[ name ] = options[ name ];
	}

	ret = callback.apply( elem, args || [] );

	// Revert the old values
	for ( name in options ) {
		elem.style[ name ] = old[ name ];
	}

	return ret;
};


var documentElement = document.documentElement;



( function() {
	var pixelPositionVal, pixelMarginRightVal, boxSizingReliableVal,
		reliableHiddenOffsetsVal, reliableMarginRightVal, reliableMarginLeftVal,
		container = document.createElement( "div" ),
		div = document.createElement( "div" );

	// Finish early in limited (non-browser) environments
	if ( !div.style ) {
		return;
	}

	div.style.cssText = "float:left;opacity:.5";

	// Support: IE<9
	// Make sure that element opacity exists (as opposed to filter)
	support.opacity = div.style.opacity === "0.5";

	// Verify style float existence
	// (IE uses styleFloat instead of cssFloat)
	support.cssFloat = !!div.style.cssFloat;

	div.style.backgroundClip = "content-box";
	div.cloneNode( true ).style.backgroundClip = "";
	support.clearCloneStyle = div.style.backgroundClip === "content-box";

	container = document.createElement( "div" );
	container.style.cssText = "border:0;width:8px;height:0;top:0;left:-9999px;" +
		"padding:0;margin-top:1px;position:absolute";
	div.innerHTML = "";
	container.appendChild( div );

	// Support: Firefox<29, Android 2.3
	// Vendor-prefix box-sizing
	support.boxSizing = div.style.boxSizing === "" || div.style.MozBoxSizing === "" ||
		div.style.WebkitBoxSizing === "";

	jQuery.extend( support, {
		reliableHiddenOffsets: function() {
			if ( pixelPositionVal == null ) {
				computeStyleTests();
			}
			return reliableHiddenOffsetsVal;
		},

		boxSizingReliable: function() {

			// We're checking for pixelPositionVal here instead of boxSizingReliableVal
			// since that compresses better and they're computed together anyway.
			if ( pixelPositionVal == null ) {
				computeStyleTests();
			}
			return boxSizingReliableVal;
		},

		pixelMarginRight: function() {

			// Support: Android 4.0-4.3
			if ( pixelPositionVal == null ) {
				computeStyleTests();
			}
			return pixelMarginRightVal;
		},

		pixelPosition: function() {
			if ( pixelPositionVal == null ) {
				computeStyleTests();
			}
			return pixelPositionVal;
		},

		reliableMarginRight: function() {

			// Support: Android 2.3
			if ( pixelPositionVal == null ) {
				computeStyleTests();
			}
			return reliableMarginRightVal;
		},

		reliableMarginLeft: function() {

			// Support: IE <=8 only, Android 4.0 - 4.3 only, Firefox <=3 - 37
			if ( pixelPositionVal == null ) {
				computeStyleTests();
			}
			return reliableMarginLeftVal;
		}
	} );

	function computeStyleTests() {
		var contents, divStyle,
			documentElement = document.documentElement;

		// Setup
		documentElement.appendChild( container );

		div.style.cssText =

			// Support: Android 2.3
			// Vendor-prefix box-sizing
			"-webkit-box-sizing:border-box;box-sizing:border-box;" +
			"position:relative;display:block;" +
			"margin:auto;border:1px;padding:1px;" +
			"top:1%;width:50%";

		// Support: IE<9
		// Assume reasonable values in the absence of getComputedStyle
		pixelPositionVal = boxSizingReliableVal = reliableMarginLeftVal = false;
		pixelMarginRightVal = reliableMarginRightVal = true;

		// Check for getComputedStyle so that this code is not run in IE<9.
		if ( window.getComputedStyle ) {
			divStyle = window.getComputedStyle( div );
			pixelPositionVal = ( divStyle || {} ).top !== "1%";
			reliableMarginLeftVal = ( divStyle || {} ).marginLeft === "2px";
			boxSizingReliableVal = ( divStyle || { width: "4px" } ).width === "4px";

			// Support: Android 4.0 - 4.3 only
			// Some styles come back with percentage values, even though they shouldn't
			div.style.marginRight = "50%";
			pixelMarginRightVal = ( divStyle || { marginRight: "4px" } ).marginRight === "4px";

			// Support: Android 2.3 only
			// Div with explicit width and no margin-right incorrectly
			// gets computed margin-right based on width of container (#3333)
			// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
			contents = div.appendChild( document.createElement( "div" ) );

			// Reset CSS: box-sizing; display; margin; border; padding
			contents.style.cssText = div.style.cssText =

				// Support: Android 2.3
				// Vendor-prefix box-sizing
				"-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" +
				"box-sizing:content-box;display:block;margin:0;border:0;padding:0";
			contents.style.marginRight = contents.style.width = "0";
			div.style.width = "1px";

			reliableMarginRightVal =
				!parseFloat( ( window.getComputedStyle( contents ) || {} ).marginRight );

			div.removeChild( contents );
		}

		// Support: IE6-8
		// First check that getClientRects works as expected
		// Check if table cells still have offsetWidth/Height when they are set
		// to display:none and there are still other visible table cells in a
		// table row; if so, offsetWidth/Height are not reliable for use when
		// determining if an element has been hidden directly using
		// display:none (it is still safe to use offsets if a parent element is
		// hidden; don safety goggles and see bug #4512 for more information).
		div.style.display = "none";
		reliableHiddenOffsetsVal = div.getClientRects().length === 0;
		if ( reliableHiddenOffsetsVal ) {
			div.style.display = "";
			div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
			div.childNodes[ 0 ].style.borderCollapse = "separate";
			contents = div.getElementsByTagName( "td" );
			contents[ 0 ].style.cssText = "margin:0;border:0;padding:0;display:none";
			reliableHiddenOffsetsVal = contents[ 0 ].offsetHeight === 0;
			if ( reliableHiddenOffsetsVal ) {
				contents[ 0 ].style.display = "";
				contents[ 1 ].style.display = "none";
				reliableHiddenOffsetsVal = contents[ 0 ].offsetHeight === 0;
			}
		}

		// Teardown
		documentElement.removeChild( container );
	}

} )();


var getStyles, curCSS,
	rposition = /^(top|right|bottom|left)$/;

if ( window.getComputedStyle ) {
	getStyles = function( elem ) {

		// Support: IE<=11+, Firefox<=30+ (#15098, #14150)
		// IE throws on elements created in popups
		// FF meanwhile throws on frame elements through "defaultView.getComputedStyle"
		var view = elem.ownerDocument.defaultView;

		if ( !view || !view.opener ) {
			view = window;
		}

		return view.getComputedStyle( elem );
	};

	curCSS = function( elem, name, computed ) {
		var width, minWidth, maxWidth, ret,
			style = elem.style;

		computed = computed || getStyles( elem );

		// getPropertyValue is only needed for .css('filter') in IE9, see #12537
		ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined;

		// Support: Opera 12.1x only
		// Fall back to style even without computed
		// computed is undefined for elems on document fragments
		if ( ( ret === "" || ret === undefined ) && !jQuery.contains( elem.ownerDocument, elem ) ) {
			ret = jQuery.style( elem, name );
		}

		if ( computed ) {

			// A tribute to the "awesome hack by Dean Edwards"
			// Chrome < 17 and Safari 5.0 uses "computed value"
			// instead of "used value" for margin-right
			// Safari 5.1.7 (at least) returns percentage for a larger set of values,
			// but width seems to be reliably pixels
			// this is against the CSSOM draft spec:
			// http://dev.w3.org/csswg/cssom/#resolved-values
			if ( !support.pixelMarginRight() && rnumnonpx.test( ret ) && rmargin.test( name ) ) {

				// Remember the original values
				width = style.width;
				minWidth = style.minWidth;
				maxWidth = style.maxWidth;

				// Put in the new values to get a computed value out
				style.minWidth = style.maxWidth = style.width = ret;
				ret = computed.width;

				// Revert the changed values
				style.width = width;
				style.minWidth = minWidth;
				style.maxWidth = maxWidth;
			}
		}

		// Support: IE
		// IE returns zIndex value as an integer.
		return ret === undefined ?
			ret :
			ret + "";
	};
} else if ( documentElement.currentStyle ) {
	getStyles = function( elem ) {
		return elem.currentStyle;
	};

	curCSS = function( elem, name, computed ) {
		var left, rs, rsLeft, ret,
			style = elem.style;

		computed = computed || getStyles( elem );
		ret = computed ? computed[ name ] : undefined;

		// Avoid setting ret to empty string here
		// so we don't default to auto
		if ( ret == null && style && style[ name ] ) {
			ret = style[ name ];
		}

		// From the awesome hack by Dean Edwards
		// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291

		// If we're not dealing with a regular pixel number
		// but a number that has a weird ending, we need to convert it to pixels
		// but not position css attributes, as those are
		// proportional to the parent element instead
		// and we can't measure the parent instead because it
		// might trigger a "stacking dolls" problem
		if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {

			// Remember the original values
			left = style.left;
			rs = elem.runtimeStyle;
			rsLeft = rs && rs.left;

			// Put in the new values to get a computed value out
			if ( rsLeft ) {
				rs.left = elem.currentStyle.left;
			}
			style.left = name === "fontSize" ? "1em" : ret;
			ret = style.pixelLeft + "px";

			// Revert the changed values
			style.left = left;
			if ( rsLeft ) {
				rs.left = rsLeft;
			}
		}

		// Support: IE
		// IE returns zIndex value as an integer.
		return ret === undefined ?
			ret :
			ret + "" || "auto";
	};
}




function addGetHookIf( conditionFn, hookFn ) {

	// Define the hook, we'll check on the first run if it's really needed.
	return {
		get: function() {
			if ( conditionFn() ) {

				// Hook not needed (or it's not possible to use it due
				// to missing dependency), remove it.
				delete this.get;
				return;
			}

			// Hook needed; redefine it so that the support test is not executed again.
			return ( this.get = hookFn ).apply( this, arguments );
		}
	};
}


var

		ralpha = /alpha\([^)]*\)/i,
	ropacity = /opacity\s*=\s*([^)]*)/i,

	// swappable if display is none or starts with table except
	// "table", "table-cell", or "table-caption"
	// see here for display values:
	// https://developer.mozilla.org/en-US/docs/CSS/display
	rdisplayswap = /^(none|table(?!-c[ea]).+)/,
	rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ),

	cssShow = { position: "absolute", visibility: "hidden", display: "block" },
	cssNormalTransform = {
		letterSpacing: "0",
		fontWeight: "400"
	},

	cssPrefixes = [ "Webkit", "O", "Moz", "ms" ],
	emptyStyle = document.createElement( "div" ).style;


// return a css property mapped to a potentially vendor prefixed property
function vendorPropName( name ) {

	// shortcut for names that are not vendor prefixed
	if ( name in emptyStyle ) {
		return name;
	}

	// check for vendor prefixed names
	var capName = name.charAt( 0 ).toUpperCase() + name.slice( 1 ),
		i = cssPrefixes.length;

	while ( i-- ) {
		name = cssPrefixes[ i ] + capName;
		if ( name in emptyStyle ) {
			return name;
		}
	}
}

function showHide( elements, show ) {
	var display, elem, hidden,
		values = [],
		index = 0,
		length = elements.length;

	for ( ; index < length; index++ ) {
		elem = elements[ index ];
		if ( !elem.style ) {
			continue;
		}

		values[ index ] = jQuery._data( elem, "olddisplay" );
		display = elem.style.display;
		if ( show ) {

			// Reset the inline display of this element to learn if it is
			// being hidden by cascaded rules or not
			if ( !values[ index ] && display === "none" ) {
				elem.style.display = "";
			}

			// Set elements which have been overridden with display: none
			// in a stylesheet to whatever the default browser style is
			// for such an element
			if ( elem.style.display === "" && isHidden( elem ) ) {
				values[ index ] =
					jQuery._data( elem, "olddisplay", defaultDisplay( elem.nodeName ) );
			}
		} else {
			hidden = isHidden( elem );

			if ( display && display !== "none" || !hidden ) {
				jQuery._data(
					elem,
					"olddisplay",
					hidden ? display : jQuery.css( elem, "display" )
				);
			}
		}
	}

	// Set the display of most of the elements in a second loop
	// to avoid the constant reflow
	for ( index = 0; index < length; index++ ) {
		elem = elements[ index ];
		if ( !elem.style ) {
			continue;
		}
		if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
			elem.style.display = show ? values[ index ] || "" : "none";
		}
	}

	return elements;
}

function setPositiveNumber( elem, value, subtract ) {
	var matches = rnumsplit.exec( value );
	return matches ?

		// Guard against undefined "subtract", e.g., when used as in cssHooks
		Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
		value;
}

function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
	var i = extra === ( isBorderBox ? "border" : "content" ) ?

		// If we already have the right measurement, avoid augmentation
		4 :

		// Otherwise initialize for horizontal or vertical properties
		name === "width" ? 1 : 0,

		val = 0;

	for ( ; i < 4; i += 2 ) {

		// both box models exclude margin, so add it if we want it
		if ( extra === "margin" ) {
			val += jQuery.css( elem, extra + cssExpand[ i ], true, styles );
		}

		if ( isBorderBox ) {

			// border-box includes padding, so remove it if we want content
			if ( extra === "content" ) {
				val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
			}

			// at this point, extra isn't border nor margin, so remove border
			if ( extra !== "margin" ) {
				val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
			}
		} else {

			// at this point, extra isn't content, so add padding
			val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );

			// at this point, extra isn't content nor padding, so add border
			if ( extra !== "padding" ) {
				val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
			}
		}
	}

	return val;
}

function getWidthOrHeight( elem, name, extra ) {

	// Start with offset property, which is equivalent to the border-box value
	var valueIsBorderBox = true,
		val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
		styles = getStyles( elem ),
		isBorderBox = support.boxSizing &&
			jQuery.css( elem, "boxSizing", false, styles ) === "border-box";

	// some non-html elements return undefined for offsetWidth, so check for null/undefined
	// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
	// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
	if ( val <= 0 || val == null ) {

		// Fall back to computed then uncomputed css if necessary
		val = curCSS( elem, name, styles );
		if ( val < 0 || val == null ) {
			val = elem.style[ name ];
		}

		// Computed unit is not pixels. Stop here and return.
		if ( rnumnonpx.test( val ) ) {
			return val;
		}

		// we need the check for style in case a browser which returns unreliable values
		// for getComputedStyle silently falls back to the reliable elem.style
		valueIsBorderBox = isBorderBox &&
			( support.boxSizingReliable() || val === elem.style[ name ] );

		// Normalize "", auto, and prepare for extra
		val = parseFloat( val ) || 0;
	}

	// use the active box-sizing model to add/subtract irrelevant styles
	return ( val +
		augmentWidthOrHeight(
			elem,
			name,
			extra || ( isBorderBox ? "border" : "content" ),
			valueIsBorderBox,
			styles
		)
	) + "px";
}

jQuery.extend( {

	// Add in style property hooks for overriding the default
	// behavior of getting and setting a style property
	cssHooks: {
		opacity: {
			get: function( elem, computed ) {
				if ( computed ) {

					// We should always get a number back from opacity
					var ret = curCSS( elem, "opacity" );
					return ret === "" ? "1" : ret;
				}
			}
		}
	},

	// Don't automatically add "px" to these possibly-unitless properties
	cssNumber: {
		"animationIterationCount": true,
		"columnCount": true,
		"fillOpacity": true,
		"flexGrow": true,
		"flexShrink": true,
		"fontWeight": true,
		"lineHeight": true,
		"opacity": true,
		"order": true,
		"orphans": true,
		"widows": true,
		"zIndex": true,
		"zoom": true
	},

	// Add in properties whose names you wish to fix before
	// setting or getting the value
	cssProps: {

		// normalize float css property
		"float": support.cssFloat ? "cssFloat" : "styleFloat"
	},

	// Get and set the style property on a DOM Node
	style: function( elem, name, value, extra ) {

		// Don't set styles on text and comment nodes
		if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
			return;
		}

		// Make sure that we're working with the right name
		var ret, type, hooks,
			origName = jQuery.camelCase( name ),
			style = elem.style;

		name = jQuery.cssProps[ origName ] ||
			( jQuery.cssProps[ origName ] = vendorPropName( origName ) || origName );

		// gets hook for the prefixed version
		// followed by the unprefixed version
		hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];

		// Check if we're setting a value
		if ( value !== undefined ) {
			type = typeof value;

			// Convert "+=" or "-=" to relative numbers (#7345)
			if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) {
				value = adjustCSS( elem, name, ret );

				// Fixes bug #9237
				type = "number";
			}

			// Make sure that null and NaN values aren't set. See: #7116
			if ( value == null || value !== value ) {
				return;
			}

			// If a number was passed in, add the unit (except for certain CSS properties)
			if ( type === "number" ) {
				value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" );
			}

			// Fixes #8908, it can be done more correctly by specifing setters in cssHooks,
			// but it would mean to define eight
			// (for every problematic property) identical functions
			if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) {
				style[ name ] = "inherit";
			}

			// If a hook was provided, use that value, otherwise just set the specified value
			if ( !hooks || !( "set" in hooks ) ||
				( value = hooks.set( elem, value, extra ) ) !== undefined ) {

				// Support: IE
				// Swallow errors from 'invalid' CSS values (#5509)
				try {
					style[ name ] = value;
				} catch ( e ) {}
			}

		} else {

			// If a hook was provided get the non-computed value from there
			if ( hooks && "get" in hooks &&
				( ret = hooks.get( elem, false, extra ) ) !== undefined ) {

				return ret;
			}

			// Otherwise just get the value from the style object
			return style[ name ];
		}
	},

	css: function( elem, name, extra, styles ) {
		var num, val, hooks,
			origName = jQuery.camelCase( name );

		// Make sure that we're working with the right name
		name = jQuery.cssProps[ origName ] ||
			( jQuery.cssProps[ origName ] = vendorPropName( origName ) || origName );

		// gets hook for the prefixed version
		// followed by the unprefixed version
		hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];

		// If a hook was provided get the computed value from there
		if ( hooks && "get" in hooks ) {
			val = hooks.get( elem, true, extra );
		}

		// Otherwise, if a way to get the computed value exists, use that
		if ( val === undefined ) {
			val = curCSS( elem, name, styles );
		}

		//convert "normal" to computed value
		if ( val === "normal" && name in cssNormalTransform ) {
			val = cssNormalTransform[ name ];
		}

		// Return, converting to number if forced or a qualifier was provided and val looks numeric
		if ( extra === "" || extra ) {
			num = parseFloat( val );
			return extra === true || isFinite( num ) ? num || 0 : val;
		}
		return val;
	}
} );

jQuery.each( [ "height", "width" ], function( i, name ) {
	jQuery.cssHooks[ name ] = {
		get: function( elem, computed, extra ) {
			if ( computed ) {

				// certain elements can have dimension info if we invisibly show them
				// however, it must have a current display style that would benefit from this
				return rdisplayswap.test( jQuery.css( elem, "display" ) ) &&
					elem.offsetWidth === 0 ?
						swap( elem, cssShow, function() {
							return getWidthOrHeight( elem, name, extra );
						} ) :
						getWidthOrHeight( elem, name, extra );
			}
		},

		set: function( elem, value, extra ) {
			var styles = extra && getStyles( elem );
			return setPositiveNumber( elem, value, extra ?
				augmentWidthOrHeight(
					elem,
					name,
					extra,
					support.boxSizing &&
						jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
					styles
				) : 0
			);
		}
	};
} );

if ( !support.opacity ) {
	jQuery.cssHooks.opacity = {
		get: function( elem, computed ) {

			// IE uses filters for opacity
			return ropacity.test( ( computed && elem.currentStyle ?
				elem.currentStyle.filter :
				elem.style.filter ) || "" ) ?
					( 0.01 * parseFloat( RegExp.$1 ) ) + "" :
					computed ? "1" : "";
		},

		set: function( elem, value ) {
			var style = elem.style,
				currentStyle = elem.currentStyle,
				opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
				filter = currentStyle && currentStyle.filter || style.filter || "";

			// IE has trouble with opacity if it does not have layout
			// Force it by setting the zoom level
			style.zoom = 1;

			// if setting opacity to 1, and no other filters exist -
			// attempt to remove filter attribute #6652
			// if value === "", then remove inline opacity #12685
			if ( ( value >= 1 || value === "" ) &&
					jQuery.trim( filter.replace( ralpha, "" ) ) === "" &&
					style.removeAttribute ) {

				// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
				// if "filter:" is present at all, clearType is disabled, we want to avoid this
				// style.removeAttribute is IE Only, but so apparently is this code path...
				style.removeAttribute( "filter" );

				// if there is no filter style applied in a css rule
				// or unset inline opacity, we are done
				if ( value === "" || currentStyle && !currentStyle.filter ) {
					return;
				}
			}

			// otherwise, set new filter values
			style.filter = ralpha.test( filter ) ?
				filter.replace( ralpha, opacity ) :
				filter + " " + opacity;
		}
	};
}

jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight,
	function( elem, computed ) {
		if ( computed ) {
			return swap( elem, { "display": "inline-block" },
				curCSS, [ elem, "marginRight" ] );
		}
	}
);

jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft,
	function( elem, computed ) {
		if ( computed ) {
			return (
				parseFloat( curCSS( elem, "marginLeft" ) ) ||

				// Support: IE<=11+
				// Running getBoundingClientRect on a disconnected node in IE throws an error
				// Support: IE8 only
				// getClientRects() errors on disconnected elems
				( jQuery.contains( elem.ownerDocument, elem ) ?
					elem.getBoundingClientRect().left -
						swap( elem, { marginLeft: 0 }, function() {
							return elem.getBoundingClientRect().left;
						} ) :
					0
				)
			) + "px";
		}
	}
);

// These hooks are used by animate to expand properties
jQuery.each( {
	margin: "",
	padding: "",
	border: "Width"
}, function( prefix, suffix ) {
	jQuery.cssHooks[ prefix + suffix ] = {
		expand: function( value ) {
			var i = 0,
				expanded = {},

				// assumes a single number if not a string
				parts = typeof value === "string" ? value.split( " " ) : [ value ];

			for ( ; i < 4; i++ ) {
				expanded[ prefix + cssExpand[ i ] + suffix ] =
					parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
			}

			return expanded;
		}
	};

	if ( !rmargin.test( prefix ) ) {
		jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
	}
} );

jQuery.fn.extend( {
	css: function( name, value ) {
		return access( this, function( elem, name, value ) {
			var styles, len,
				map = {},
				i = 0;

			if ( jQuery.isArray( name ) ) {
				styles = getStyles( elem );
				len = name.length;

				for ( ; i < len; i++ ) {
					map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
				}

				return map;
			}

			return value !== undefined ?
				jQuery.style( elem, name, value ) :
				jQuery.css( elem, name );
		}, name, value, arguments.length > 1 );
	},
	show: function() {
		return showHide( this, true );
	},
	hide: function() {
		return showHide( this );
	},
	toggle: function( state ) {
		if ( typeof state === "boolean" ) {
			return state ? this.show() : this.hide();
		}

		return this.each( function() {
			if ( isHidden( this ) ) {
				jQuery( this ).show();
			} else {
				jQuery( this ).hide();
			}
		} );
	}
} );


function Tween( elem, options, prop, end, easing ) {
	return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;

Tween.prototype = {
	constructor: Tween,
	init: function( elem, options, prop, end, easing, unit ) {
		this.elem = elem;
		this.prop = prop;
		this.easing = easing || jQuery.easing._default;
		this.options = options;
		this.start = this.now = this.cur();
		this.end = end;
		this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
	},
	cur: function() {
		var hooks = Tween.propHooks[ this.prop ];

		return hooks && hooks.get ?
			hooks.get( this ) :
			Tween.propHooks._default.get( this );
	},
	run: function( percent ) {
		var eased,
			hooks = Tween.propHooks[ this.prop ];

		if ( this.options.duration ) {
			this.pos = eased = jQuery.easing[ this.easing ](
				percent, this.options.duration * percent, 0, 1, this.options.duration
			);
		} else {
			this.pos = eased = percent;
		}
		this.now = ( this.end - this.start ) * eased + this.start;

		if ( this.options.step ) {
			this.options.step.call( this.elem, this.now, this );
		}

		if ( hooks && hooks.set ) {
			hooks.set( this );
		} else {
			Tween.propHooks._default.set( this );
		}
		return this;
	}
};

Tween.prototype.init.prototype = Tween.prototype;

Tween.propHooks = {
	_default: {
		get: function( tween ) {
			var result;

			// Use a property on the element directly when it is not a DOM element,
			// or when there is no matching style property that exists.
			if ( tween.elem.nodeType !== 1 ||
				tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) {
				return tween.elem[ tween.prop ];
			}

			// passing an empty string as a 3rd parameter to .css will automatically
			// attempt a parseFloat and fallback to a string if the parse fails
			// so, simple values such as "10px" are parsed to Float.
			// complex values such as "rotate(1rad)" are returned as is.
			result = jQuery.css( tween.elem, tween.prop, "" );

			// Empty strings, null, undefined and "auto" are converted to 0.
			return !result || result === "auto" ? 0 : result;
		},
		set: function( tween ) {

			// use step hook for back compat - use cssHook if its there - use .style if its
			// available and use plain properties where available
			if ( jQuery.fx.step[ tween.prop ] ) {
				jQuery.fx.step[ tween.prop ]( tween );
			} else if ( tween.elem.nodeType === 1 &&
				( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null ||
					jQuery.cssHooks[ tween.prop ] ) ) {
				jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
			} else {
				tween.elem[ tween.prop ] = tween.now;
			}
		}
	}
};

// Support: IE <=9
// Panic based approach to setting things on disconnected nodes

Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
	set: function( tween ) {
		if ( tween.elem.nodeType && tween.elem.parentNode ) {
			tween.elem[ tween.prop ] = tween.now;
		}
	}
};

jQuery.easing = {
	linear: function( p ) {
		return p;
	},
	swing: function( p ) {
		return 0.5 - Math.cos( p * Math.PI ) / 2;
	},
	_default: "swing"
};

jQuery.fx = Tween.prototype.init;

// Back Compat <1.8 extension point
jQuery.fx.step = {};




var
	fxNow, timerId,
	rfxtypes = /^(?:toggle|show|hide)$/,
	rrun = /queueHooks$/;

// Animations created synchronously will run synchronously
function createFxNow() {
	window.setTimeout( function() {
		fxNow = undefined;
	} );
	return ( fxNow = jQuery.now() );
}

// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
	var which,
		attrs = { height: type },
		i = 0;

	// if we include width, step value is 1 to do all cssExpand values,
	// if we don't include width, step value is 2 to skip over Left and Right
	includeWidth = includeWidth ? 1 : 0;
	for ( ; i < 4 ; i += 2 - includeWidth ) {
		which = cssExpand[ i ];
		attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
	}

	if ( includeWidth ) {
		attrs.opacity = attrs.width = type;
	}

	return attrs;
}

function createTween( value, prop, animation ) {
	var tween,
		collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ),
		index = 0,
		length = collection.length;
	for ( ; index < length; index++ ) {
		if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) {

			// we're done with this property
			return tween;
		}
	}
}

function defaultPrefilter( elem, props, opts ) {
	/* jshint validthis: true */
	var prop, value, toggle, tween, hooks, oldfire, display, checkDisplay,
		anim = this,
		orig = {},
		style = elem.style,
		hidden = elem.nodeType && isHidden( elem ),
		dataShow = jQuery._data( elem, "fxshow" );

	// handle queue: false promises
	if ( !opts.queue ) {
		hooks = jQuery._queueHooks( elem, "fx" );
		if ( hooks.unqueued == null ) {
			hooks.unqueued = 0;
			oldfire = hooks.empty.fire;
			hooks.empty.fire = function() {
				if ( !hooks.unqueued ) {
					oldfire();
				}
			};
		}
		hooks.unqueued++;

		anim.always( function() {

			// doing this makes sure that the complete handler will be called
			// before this completes
			anim.always( function() {
				hooks.unqueued--;
				if ( !jQuery.queue( elem, "fx" ).length ) {
					hooks.empty.fire();
				}
			} );
		} );
	}

	// height/width overflow pass
	if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {

		// Make sure that nothing sneaks out
		// Record all 3 overflow attributes because IE does not
		// change the overflow attribute when overflowX and
		// overflowY are set to the same value
		opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];

		// Set display property to inline-block for height/width
		// animations on inline elements that are having width/height animated
		display = jQuery.css( elem, "display" );

		// Test default display if display is currently "none"
		checkDisplay = display === "none" ?
			jQuery._data( elem, "olddisplay" ) || defaultDisplay( elem.nodeName ) : display;

		if ( checkDisplay === "inline" && jQuery.css( elem, "float" ) === "none" ) {

			// inline-level elements accept inline-block;
			// block-level elements need to be inline with layout
			if ( !support.inlineBlockNeedsLayout || defaultDisplay( elem.nodeName ) === "inline" ) {
				style.display = "inline-block";
			} else {
				style.zoom = 1;
			}
		}
	}

	if ( opts.overflow ) {
		style.overflow = "hidden";
		if ( !support.shrinkWrapBlocks() ) {
			anim.always( function() {
				style.overflow = opts.overflow[ 0 ];
				style.overflowX = opts.overflow[ 1 ];
				style.overflowY = opts.overflow[ 2 ];
			} );
		}
	}

	// show/hide pass
	for ( prop in props ) {
		value = props[ prop ];
		if ( rfxtypes.exec( value ) ) {
			delete props[ prop ];
			toggle = toggle || value === "toggle";
			if ( value === ( hidden ? "hide" : "show" ) ) {

				// If there is dataShow left over from a stopped hide or show
				// and we are going to proceed with show, we should pretend to be hidden
				if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) {
					hidden = true;
				} else {
					continue;
				}
			}
			orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );

		// Any non-fx value stops us from restoring the original display value
		} else {
			display = undefined;
		}
	}

	if ( !jQuery.isEmptyObject( orig ) ) {
		if ( dataShow ) {
			if ( "hidden" in dataShow ) {
				hidden = dataShow.hidden;
			}
		} else {
			dataShow = jQuery._data( elem, "fxshow", {} );
		}

		// store state if its toggle - enables .stop().toggle() to "reverse"
		if ( toggle ) {
			dataShow.hidden = !hidden;
		}
		if ( hidden ) {
			jQuery( elem ).show();
		} else {
			anim.done( function() {
				jQuery( elem ).hide();
			} );
		}
		anim.done( function() {
			var prop;
			jQuery._removeData( elem, "fxshow" );
			for ( prop in orig ) {
				jQuery.style( elem, prop, orig[ prop ] );
			}
		} );
		for ( prop in orig ) {
			tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );

			if ( !( prop in dataShow ) ) {
				dataShow[ prop ] = tween.start;
				if ( hidden ) {
					tween.end = tween.start;
					tween.start = prop === "width" || prop === "height" ? 1 : 0;
				}
			}
		}

	// If this is a noop like .hide().hide(), restore an overwritten display value
	} else if ( ( display === "none" ? defaultDisplay( elem.nodeName ) : display ) === "inline" ) {
		style.display = display;
	}
}

function propFilter( props, specialEasing ) {
	var index, name, easing, value, hooks;

	// camelCase, specialEasing and expand cssHook pass
	for ( index in props ) {
		name = jQuery.camelCase( index );
		easing = specialEasing[ name ];
		value = props[ index ];
		if ( jQuery.isArray( value ) ) {
			easing = value[ 1 ];
			value = props[ index ] = value[ 0 ];
		}

		if ( index !== name ) {
			props[ name ] = value;
			delete props[ index ];
		}

		hooks = jQuery.cssHooks[ name ];
		if ( hooks && "expand" in hooks ) {
			value = hooks.expand( value );
			delete props[ name ];

			// not quite $.extend, this wont overwrite keys already present.
			// also - reusing 'index' from above because we have the correct "name"
			for ( index in value ) {
				if ( !( index in props ) ) {
					props[ index ] = value[ index ];
					specialEasing[ index ] = easing;
				}
			}
		} else {
			specialEasing[ name ] = easing;
		}
	}
}

function Animation( elem, properties, options ) {
	var result,
		stopped,
		index = 0,
		length = Animation.prefilters.length,
		deferred = jQuery.Deferred().always( function() {

			// don't match elem in the :animated selector
			delete tick.elem;
		} ),
		tick = function() {
			if ( stopped ) {
				return false;
			}
			var currentTime = fxNow || createFxNow(),
				remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),

				// Support: Android 2.3
				// Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497)
				temp = remaining / animation.duration || 0,
				percent = 1 - temp,
				index = 0,
				length = animation.tweens.length;

			for ( ; index < length ; index++ ) {
				animation.tweens[ index ].run( percent );
			}

			deferred.notifyWith( elem, [ animation, percent, remaining ] );

			if ( percent < 1 && length ) {
				return remaining;
			} else {
				deferred.resolveWith( elem, [ animation ] );
				return false;
			}
		},
		animation = deferred.promise( {
			elem: elem,
			props: jQuery.extend( {}, properties ),
			opts: jQuery.extend( true, {
				specialEasing: {},
				easing: jQuery.easing._default
			}, options ),
			originalProperties: properties,
			originalOptions: options,
			startTime: fxNow || createFxNow(),
			duration: options.duration,
			tweens: [],
			createTween: function( prop, end ) {
				var tween = jQuery.Tween( elem, animation.opts, prop, end,
						animation.opts.specialEasing[ prop ] || animation.opts.easing );
				animation.tweens.push( tween );
				return tween;
			},
			stop: function( gotoEnd ) {
				var index = 0,

					// if we are going to the end, we want to run all the tweens
					// otherwise we skip this part
					length = gotoEnd ? animation.tweens.length : 0;
				if ( stopped ) {
					return this;
				}
				stopped = true;
				for ( ; index < length ; index++ ) {
					animation.tweens[ index ].run( 1 );
				}

				// resolve when we played the last frame
				// otherwise, reject
				if ( gotoEnd ) {
					deferred.notifyWith( elem, [ animation, 1, 0 ] );
					deferred.resolveWith( elem, [ animation, gotoEnd ] );
				} else {
					deferred.rejectWith( elem, [ animation, gotoEnd ] );
				}
				return this;
			}
		} ),
		props = animation.props;

	propFilter( props, animation.opts.specialEasing );

	for ( ; index < length ; index++ ) {
		result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts );
		if ( result ) {
			if ( jQuery.isFunction( result.stop ) ) {
				jQuery._queueHooks( animation.elem, animation.opts.queue ).stop =
					jQuery.proxy( result.stop, result );
			}
			return result;
		}
	}

	jQuery.map( props, createTween, animation );

	if ( jQuery.isFunction( animation.opts.start ) ) {
		animation.opts.start.call( elem, animation );
	}

	jQuery.fx.timer(
		jQuery.extend( tick, {
			elem: elem,
			anim: animation,
			queue: animation.opts.queue
		} )
	);

	// attach callbacks from options
	return animation.progress( animation.opts.progress )
		.done( animation.opts.done, animation.opts.complete )
		.fail( animation.opts.fail )
		.always( animation.opts.always );
}

jQuery.Animation = jQuery.extend( Animation, {

	tweeners: {
		"*": [ function( prop, value ) {
			var tween = this.createTween( prop, value );
			adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween );
			return tween;
		} ]
	},

	tweener: function( props, callback ) {
		if ( jQuery.isFunction( props ) ) {
			callback = props;
			props = [ "*" ];
		} else {
			props = props.match( rnotwhite );
		}

		var prop,
			index = 0,
			length = props.length;

		for ( ; index < length ; index++ ) {
			prop = props[ index ];
			Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || [];
			Animation.tweeners[ prop ].unshift( callback );
		}
	},

	prefilters: [ defaultPrefilter ],

	prefilter: function( callback, prepend ) {
		if ( prepend ) {
			Animation.prefilters.unshift( callback );
		} else {
			Animation.prefilters.push( callback );
		}
	}
} );

jQuery.speed = function( speed, easing, fn ) {
	var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
		complete: fn || !fn && easing ||
			jQuery.isFunction( speed ) && speed,
		duration: speed,
		easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
	};

	opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
		opt.duration in jQuery.fx.speeds ?
			jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;

	// normalize opt.queue - true/undefined/null -> "fx"
	if ( opt.queue == null || opt.queue === true ) {
		opt.queue = "fx";
	}

	// Queueing
	opt.old = opt.complete;

	opt.complete = function() {
		if ( jQuery.isFunction( opt.old ) ) {
			opt.old.call( this );
		}

		if ( opt.queue ) {
			jQuery.dequeue( this, opt.queue );
		}
	};

	return opt;
};

jQuery.fn.extend( {
	fadeTo: function( speed, to, easing, callback ) {

		// show any hidden elements after setting opacity to 0
		return this.filter( isHidden ).css( "opacity", 0 ).show()

			// animate to the value specified
			.end().animate( { opacity: to }, speed, easing, callback );
	},
	animate: function( prop, speed, easing, callback ) {
		var empty = jQuery.isEmptyObject( prop ),
			optall = jQuery.speed( speed, easing, callback ),
			doAnimation = function() {

				// Operate on a copy of prop so per-property easing won't be lost
				var anim = Animation( this, jQuery.extend( {}, prop ), optall );

				// Empty animations, or finishing resolves immediately
				if ( empty || jQuery._data( this, "finish" ) ) {
					anim.stop( true );
				}
			};
			doAnimation.finish = doAnimation;

		return empty || optall.queue === false ?
			this.each( doAnimation ) :
			this.queue( optall.queue, doAnimation );
	},
	stop: function( type, clearQueue, gotoEnd ) {
		var stopQueue = function( hooks ) {
			var stop = hooks.stop;
			delete hooks.stop;
			stop( gotoEnd );
		};

		if ( typeof type !== "string" ) {
			gotoEnd = clearQueue;
			clearQueue = type;
			type = undefined;
		}
		if ( clearQueue && type !== false ) {
			this.queue( type || "fx", [] );
		}

		return this.each( function() {
			var dequeue = true,
				index = type != null && type + "queueHooks",
				timers = jQuery.timers,
				data = jQuery._data( this );

			if ( index ) {
				if ( data[ index ] && data[ index ].stop ) {
					stopQueue( data[ index ] );
				}
			} else {
				for ( index in data ) {
					if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
						stopQueue( data[ index ] );
					}
				}
			}

			for ( index = timers.length; index--; ) {
				if ( timers[ index ].elem === this &&
					( type == null || timers[ index ].queue === type ) ) {

					timers[ index ].anim.stop( gotoEnd );
					dequeue = false;
					timers.splice( index, 1 );
				}
			}

			// start the next in the queue if the last step wasn't forced
			// timers currently will call their complete callbacks, which will dequeue
			// but only if they were gotoEnd
			if ( dequeue || !gotoEnd ) {
				jQuery.dequeue( this, type );
			}
		} );
	},
	finish: function( type ) {
		if ( type !== false ) {
			type = type || "fx";
		}
		return this.each( function() {
			var index,
				data = jQuery._data( this ),
				queue = data[ type + "queue" ],
				hooks = data[ type + "queueHooks" ],
				timers = jQuery.timers,
				length = queue ? queue.length : 0;

			// enable finishing flag on private data
			data.finish = true;

			// empty the queue first
			jQuery.queue( this, type, [] );

			if ( hooks && hooks.stop ) {
				hooks.stop.call( this, true );
			}

			// look for any active animations, and finish them
			for ( index = timers.length; index--; ) {
				if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
					timers[ index ].anim.stop( true );
					timers.splice( index, 1 );
				}
			}

			// look for any animations in the old queue and finish them
			for ( index = 0; index < length; index++ ) {
				if ( queue[ index ] && queue[ index ].finish ) {
					queue[ index ].finish.call( this );
				}
			}

			// turn off finishing flag
			delete data.finish;
		} );
	}
} );

jQuery.each( [ "toggle", "show", "hide" ], function( i, name ) {
	var cssFn = jQuery.fn[ name ];
	jQuery.fn[ name ] = function( speed, easing, callback ) {
		return speed == null || typeof speed === "boolean" ?
			cssFn.apply( this, arguments ) :
			this.animate( genFx( name, true ), speed, easing, callback );
	};
} );

// Generate shortcuts for custom animations
jQuery.each( {
	slideDown: genFx( "show" ),
	slideUp: genFx( "hide" ),
	slideToggle: genFx( "toggle" ),
	fadeIn: { opacity: "show" },
	fadeOut: { opacity: "hide" },
	fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
	jQuery.fn[ name ] = function( speed, easing, callback ) {
		return this.animate( props, speed, easing, callback );
	};
} );

jQuery.timers = [];
jQuery.fx.tick = function() {
	var timer,
		timers = jQuery.timers,
		i = 0;

	fxNow = jQuery.now();

	for ( ; i < timers.length; i++ ) {
		timer = timers[ i ];

		// Checks the timer has not already been removed
		if ( !timer() && timers[ i ] === timer ) {
			timers.splice( i--, 1 );
		}
	}

	if ( !timers.length ) {
		jQuery.fx.stop();
	}
	fxNow = undefined;
};

jQuery.fx.timer = function( timer ) {
	jQuery.timers.push( timer );
	if ( timer() ) {
		jQuery.fx.start();
	} else {
		jQuery.timers.pop();
	}
};

jQuery.fx.interval = 13;

jQuery.fx.start = function() {
	if ( !timerId ) {
		timerId = window.setInterval( jQuery.fx.tick, jQuery.fx.interval );
	}
};

jQuery.fx.stop = function() {
	window.clearInterval( timerId );
	timerId = null;
};

jQuery.fx.speeds = {
	slow: 600,
	fast: 200,

	// Default speed
	_default: 400
};


// Based off of the plugin by Clint Helfers, with permission.
// http://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/
jQuery.fn.delay = function( time, type ) {
	time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
	type = type || "fx";

	return this.queue( type, function( next, hooks ) {
		var timeout = window.setTimeout( next, time );
		hooks.stop = function() {
			window.clearTimeout( timeout );
		};
	} );
};


( function() {
	var a,
		input = document.createElement( "input" ),
		div = document.createElement( "div" ),
		select = document.createElement( "select" ),
		opt = select.appendChild( document.createElement( "option" ) );

	// Setup
	div = document.createElement( "div" );
	div.setAttribute( "className", "t" );
	div.innerHTML = "  <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
	a = div.getElementsByTagName( "a" )[ 0 ];

	// Support: Windows Web Apps (WWA)
	// `type` must use .setAttribute for WWA (#14901)
	input.setAttribute( "type", "checkbox" );
	div.appendChild( input );

	a = div.getElementsByTagName( "a" )[ 0 ];

	// First batch of tests.
	a.style.cssText = "top:1px";

	// Test setAttribute on camelCase class.
	// If it works, we need attrFixes when doing get/setAttribute (ie6/7)
	support.getSetAttribute = div.className !== "t";

	// Get the style information from getAttribute
	// (IE uses .cssText instead)
	support.style = /top/.test( a.getAttribute( "style" ) );

	// Make sure that URLs aren't manipulated
	// (IE normalizes it by default)
	support.hrefNormalized = a.getAttribute( "href" ) === "/a";

	// Check the default checkbox/radio value ("" on WebKit; "on" elsewhere)
	support.checkOn = !!input.value;

	// Make sure that a selected-by-default option has a working selected property.
	// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
	support.optSelected = opt.selected;

	// Tests for enctype support on a form (#6743)
	support.enctype = !!document.createElement( "form" ).enctype;

	// Make sure that the options inside disabled selects aren't marked as disabled
	// (WebKit marks them as disabled)
	select.disabled = true;
	support.optDisabled = !opt.disabled;

	// Support: IE8 only
	// Check if we can trust getAttribute("value")
	input = document.createElement( "input" );
	input.setAttribute( "value", "" );
	support.input = input.getAttribute( "value" ) === "";

	// Check if an input maintains its value after becoming a radio
	input.value = "t";
	input.setAttribute( "type", "radio" );
	support.radioValue = input.value === "t";
} )();


var rreturn = /\r/g,
	rspaces = /[\x20\t\r\n\f]+/g;

jQuery.fn.extend( {
	val: function( value ) {
		var hooks, ret, isFunction,
			elem = this[ 0 ];

		if ( !arguments.length ) {
			if ( elem ) {
				hooks = jQuery.valHooks[ elem.type ] ||
					jQuery.valHooks[ elem.nodeName.toLowerCase() ];

				if (
					hooks &&
					"get" in hooks &&
					( ret = hooks.get( elem, "value" ) ) !== undefined
				) {
					return ret;
				}

				ret = elem.value;

				return typeof ret === "string" ?

					// handle most common string cases
					ret.replace( rreturn, "" ) :

					// handle cases where value is null/undef or number
					ret == null ? "" : ret;
			}

			return;
		}

		isFunction = jQuery.isFunction( value );

		return this.each( function( i ) {
			var val;

			if ( this.nodeType !== 1 ) {
				return;
			}

			if ( isFunction ) {
				val = value.call( this, i, jQuery( this ).val() );
			} else {
				val = value;
			}

			// Treat null/undefined as ""; convert numbers to string
			if ( val == null ) {
				val = "";
			} else if ( typeof val === "number" ) {
				val += "";
			} else if ( jQuery.isArray( val ) ) {
				val = jQuery.map( val, function( value ) {
					return value == null ? "" : value + "";
				} );
			}

			hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];

			// If set returns undefined, fall back to normal setting
			if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) {
				this.value = val;
			}
		} );
	}
} );

jQuery.extend( {
	valHooks: {
		option: {
			get: function( elem ) {
				var val = jQuery.find.attr( elem, "value" );
				return val != null ?
					val :

					// Support: IE10-11+
					// option.text throws exceptions (#14686, #14858)
					// Strip and collapse whitespace
					// https://html.spec.whatwg.org/#strip-and-collapse-whitespace
					jQuery.trim( jQuery.text( elem ) ).replace( rspaces, " " );
			}
		},
		select: {
			get: function( elem ) {
				var value, option,
					options = elem.options,
					index = elem.selectedIndex,
					one = elem.type === "select-one" || index < 0,
					values = one ? null : [],
					max = one ? index + 1 : options.length,
					i = index < 0 ?
						max :
						one ? index : 0;

				// Loop through all the selected options
				for ( ; i < max; i++ ) {
					option = options[ i ];

					// oldIE doesn't update selected after form reset (#2551)
					if ( ( option.selected || i === index ) &&

							// Don't return options that are disabled or in a disabled optgroup
							( support.optDisabled ?
								!option.disabled :
								option.getAttribute( "disabled" ) === null ) &&
							( !option.parentNode.disabled ||
								!jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {

						// Get the specific value for the option
						value = jQuery( option ).val();

						// We don't need an array for one selects
						if ( one ) {
							return value;
						}

						// Multi-Selects return an array
						values.push( value );
					}
				}

				return values;
			},

			set: function( elem, value ) {
				var optionSet, option,
					options = elem.options,
					values = jQuery.makeArray( value ),
					i = options.length;

				while ( i-- ) {
					option = options[ i ];

					if ( jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1 ) {

						// Support: IE6
						// When new option element is added to select box we need to
						// force reflow of newly added node in order to workaround delay
						// of initialization properties
						try {
							option.selected = optionSet = true;

						} catch ( _ ) {

							// Will be executed only in IE6
							option.scrollHeight;
						}

					} else {
						option.selected = false;
					}
				}

				// Force browsers to behave consistently when non-matching value is set
				if ( !optionSet ) {
					elem.selectedIndex = -1;
				}

				return options;
			}
		}
	}
} );

// Radios and checkboxes getter/setter
jQuery.each( [ "radio", "checkbox" ], function() {
	jQuery.valHooks[ this ] = {
		set: function( elem, value ) {
			if ( jQuery.isArray( value ) ) {
				return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 );
			}
		}
	};
	if ( !support.checkOn ) {
		jQuery.valHooks[ this ].get = function( elem ) {
			return elem.getAttribute( "value" ) === null ? "on" : elem.value;
		};
	}
} );




var nodeHook, boolHook,
	attrHandle = jQuery.expr.attrHandle,
	ruseDefault = /^(?:checked|selected)$/i,
	getSetAttribute = support.getSetAttribute,
	getSetInput = support.input;

jQuery.fn.extend( {
	attr: function( name, value ) {
		return access( this, jQuery.attr, name, value, arguments.length > 1 );
	},

	removeAttr: function( name ) {
		return this.each( function() {
			jQuery.removeAttr( this, name );
		} );
	}
} );

jQuery.extend( {
	attr: function( elem, name, value ) {
		var ret, hooks,
			nType = elem.nodeType;

		// Don't get/set attributes on text, comment and attribute nodes
		if ( nType === 3 || nType === 8 || nType === 2 ) {
			return;
		}

		// Fallback to prop when attributes are not supported
		if ( typeof elem.getAttribute === "undefined" ) {
			return jQuery.prop( elem, name, value );
		}

		// All attributes are lowercase
		// Grab necessary hook if one is defined
		if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
			name = name.toLowerCase();
			hooks = jQuery.attrHooks[ name ] ||
				( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook );
		}

		if ( value !== undefined ) {
			if ( value === null ) {
				jQuery.removeAttr( elem, name );
				return;
			}

			if ( hooks && "set" in hooks &&
				( ret = hooks.set( elem, value, name ) ) !== undefined ) {
				return ret;
			}

			elem.setAttribute( name, value + "" );
			return value;
		}

		if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) {
			return ret;
		}

		ret = jQuery.find.attr( elem, name );

		// Non-existent attributes return null, we normalize to undefined
		return ret == null ? undefined : ret;
	},

	attrHooks: {
		type: {
			set: function( elem, value ) {
				if ( !support.radioValue && value === "radio" &&
					jQuery.nodeName( elem, "input" ) ) {

					// Setting the type on a radio button after the value resets the value in IE8-9
					// Reset value to default in case type is set after value during creation
					var val = elem.value;
					elem.setAttribute( "type", value );
					if ( val ) {
						elem.value = val;
					}
					return value;
				}
			}
		}
	},

	removeAttr: function( elem, value ) {
		var name, propName,
			i = 0,
			attrNames = value && value.match( rnotwhite );

		if ( attrNames && elem.nodeType === 1 ) {
			while ( ( name = attrNames[ i++ ] ) ) {
				propName = jQuery.propFix[ name ] || name;

				// Boolean attributes get special treatment (#10870)
				if ( jQuery.expr.match.bool.test( name ) ) {

					// Set corresponding property to false
					if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
						elem[ propName ] = false;

					// Support: IE<9
					// Also clear defaultChecked/defaultSelected (if appropriate)
					} else {
						elem[ jQuery.camelCase( "default-" + name ) ] =
							elem[ propName ] = false;
					}

				// See #9699 for explanation of this approach (setting first, then removal)
				} else {
					jQuery.attr( elem, name, "" );
				}

				elem.removeAttribute( getSetAttribute ? name : propName );
			}
		}
	}
} );

// Hooks for boolean attributes
boolHook = {
	set: function( elem, value, name ) {
		if ( value === false ) {

			// Remove boolean attributes when set to false
			jQuery.removeAttr( elem, name );
		} else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {

			// IE<8 needs the *property* name
			elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name );

		} else {

			// Support: IE<9
			// Use defaultChecked and defaultSelected for oldIE
			elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true;
		}
		return name;
	}
};

jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
	var getter = attrHandle[ name ] || jQuery.find.attr;

	if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
		attrHandle[ name ] = function( elem, name, isXML ) {
			var ret, handle;
			if ( !isXML ) {

				// Avoid an infinite loop by temporarily removing this function from the getter
				handle = attrHandle[ name ];
				attrHandle[ name ] = ret;
				ret = getter( elem, name, isXML ) != null ?
					name.toLowerCase() :
					null;
				attrHandle[ name ] = handle;
			}
			return ret;
		};
	} else {
		attrHandle[ name ] = function( elem, name, isXML ) {
			if ( !isXML ) {
				return elem[ jQuery.camelCase( "default-" + name ) ] ?
					name.toLowerCase() :
					null;
			}
		};
	}
} );

// fix oldIE attroperties
if ( !getSetInput || !getSetAttribute ) {
	jQuery.attrHooks.value = {
		set: function( elem, value, name ) {
			if ( jQuery.nodeName( elem, "input" ) ) {

				// Does not return so that setAttribute is also used
				elem.defaultValue = value;
			} else {

				// Use nodeHook if defined (#1954); otherwise setAttribute is fine
				return nodeHook && nodeHook.set( elem, value, name );
			}
		}
	};
}

// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {

	// Use this for any attribute in IE6/7
	// This fixes almost every IE6/7 issue
	nodeHook = {
		set: function( elem, value, name ) {

			// Set the existing or create a new attribute node
			var ret = elem.getAttributeNode( name );
			if ( !ret ) {
				elem.setAttributeNode(
					( ret = elem.ownerDocument.createAttribute( name ) )
				);
			}

			ret.value = value += "";

			// Break association with cloned elements by also using setAttribute (#9646)
			if ( name === "value" || value === elem.getAttribute( name ) ) {
				return value;
			}
		}
	};

	// Some attributes are constructed with empty-string values when not defined
	attrHandle.id = attrHandle.name = attrHandle.coords =
		function( elem, name, isXML ) {
			var ret;
			if ( !isXML ) {
				return ( ret = elem.getAttributeNode( name ) ) && ret.value !== "" ?
					ret.value :
					null;
			}
		};

	// Fixing value retrieval on a button requires this module
	jQuery.valHooks.button = {
		get: function( elem, name ) {
			var ret = elem.getAttributeNode( name );
			if ( ret && ret.specified ) {
				return ret.value;
			}
		},
		set: nodeHook.set
	};

	// Set contenteditable to false on removals(#10429)
	// Setting to empty string throws an error as an invalid value
	jQuery.attrHooks.contenteditable = {
		set: function( elem, value, name ) {
			nodeHook.set( elem, value === "" ? false : value, name );
		}
	};

	// Set width and height to auto instead of 0 on empty string( Bug #8150 )
	// This is for removals
	jQuery.each( [ "width", "height" ], function( i, name ) {
		jQuery.attrHooks[ name ] = {
			set: function( elem, value ) {
				if ( value === "" ) {
					elem.setAttribute( name, "auto" );
					return value;
				}
			}
		};
	} );
}

if ( !support.style ) {
	jQuery.attrHooks.style = {
		get: function( elem ) {

			// Return undefined in the case of empty string
			// Note: IE uppercases css property names, but if we were to .toLowerCase()
			// .cssText, that would destroy case sensitivity in URL's, like in "background"
			return elem.style.cssText || undefined;
		},
		set: function( elem, value ) {
			return ( elem.style.cssText = value + "" );
		}
	};
}




var rfocusable = /^(?:input|select|textarea|button|object)$/i,
	rclickable = /^(?:a|area)$/i;

jQuery.fn.extend( {
	prop: function( name, value ) {
		return access( this, jQuery.prop, name, value, arguments.length > 1 );
	},

	removeProp: function( name ) {
		name = jQuery.propFix[ name ] || name;
		return this.each( function() {

			// try/catch handles cases where IE balks (such as removing a property on window)
			try {
				this[ name ] = undefined;
				delete this[ name ];
			} catch ( e ) {}
		} );
	}
} );

jQuery.extend( {
	prop: function( elem, name, value ) {
		var ret, hooks,
			nType = elem.nodeType;

		// Don't get/set properties on text, comment and attribute nodes
		if ( nType === 3 || nType === 8 || nType === 2 ) {
			return;
		}

		if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {

			// Fix name and attach hooks
			name = jQuery.propFix[ name ] || name;
			hooks = jQuery.propHooks[ name ];
		}

		if ( value !== undefined ) {
			if ( hooks && "set" in hooks &&
				( ret = hooks.set( elem, value, name ) ) !== undefined ) {
				return ret;
			}

			return ( elem[ name ] = value );
		}

		if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) {
			return ret;
		}

		return elem[ name ];
	},

	propHooks: {
		tabIndex: {
			get: function( elem ) {

				// elem.tabIndex doesn't always return the
				// correct value when it hasn't been explicitly set
				// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
				// Use proper attribute retrieval(#12072)
				var tabindex = jQuery.find.attr( elem, "tabindex" );

				return tabindex ?
					parseInt( tabindex, 10 ) :
					rfocusable.test( elem.nodeName ) ||
						rclickable.test( elem.nodeName ) && elem.href ?
							0 :
							-1;
			}
		}
	},

	propFix: {
		"for": "htmlFor",
		"class": "className"
	}
} );

// Some attributes require a special call on IE
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !support.hrefNormalized ) {

	// href/src property should get the full normalized URL (#10299/#12915)
	jQuery.each( [ "href", "src" ], function( i, name ) {
		jQuery.propHooks[ name ] = {
			get: function( elem ) {
				return elem.getAttribute( name, 4 );
			}
		};
	} );
}

// Support: Safari, IE9+
// Accessing the selectedIndex property
// forces the browser to respect setting selected
// on the option
// The getter ensures a default option is selected
// when in an optgroup
if ( !support.optSelected ) {
	jQuery.propHooks.selected = {
		get: function( elem ) {
			var parent = elem.parentNode;

			if ( parent ) {
				parent.selectedIndex;

				// Make sure that it also works with optgroups, see #5701
				if ( parent.parentNode ) {
					parent.parentNode.selectedIndex;
				}
			}
			return null;
		},
		set: function( elem ) {
			var parent = elem.parentNode;
			if ( parent ) {
				parent.selectedIndex;

				if ( parent.parentNode ) {
					parent.parentNode.selectedIndex;
				}
			}
		}
	};
}

jQuery.each( [
	"tabIndex",
	"readOnly",
	"maxLength",
	"cellSpacing",
	"cellPadding",
	"rowSpan",
	"colSpan",
	"useMap",
	"frameBorder",
	"contentEditable"
], function() {
	jQuery.propFix[ this.toLowerCase() ] = this;
} );

// IE6/7 call enctype encoding
if ( !support.enctype ) {
	jQuery.propFix.enctype = "encoding";
}




var rclass = /[\t\r\n\f]/g;

function getClass( elem ) {
	return jQuery.attr( elem, "class" ) || "";
}

jQuery.fn.extend( {
	addClass: function( value ) {
		var classes, elem, cur, curValue, clazz, j, finalValue,
			i = 0;

		if ( jQuery.isFunction( value ) ) {
			return this.each( function( j ) {
				jQuery( this ).addClass( value.call( this, j, getClass( this ) ) );
			} );
		}

		if ( typeof value === "string" && value ) {
			classes = value.match( rnotwhite ) || [];

			while ( ( elem = this[ i++ ] ) ) {
				curValue = getClass( elem );
				cur = elem.nodeType === 1 &&
					( " " + curValue + " " ).replace( rclass, " " );

				if ( cur ) {
					j = 0;
					while ( ( clazz = classes[ j++ ] ) ) {
						if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
							cur += clazz + " ";
						}
					}

					// only assign if different to avoid unneeded rendering.
					finalValue = jQuery.trim( cur );
					if ( curValue !== finalValue ) {
						jQuery.attr( elem, "class", finalValue );
					}
				}
			}
		}

		return this;
	},

	removeClass: function( value ) {
		var classes, elem, cur, curValue, clazz, j, finalValue,
			i = 0;

		if ( jQuery.isFunction( value ) ) {
			return this.each( function( j ) {
				jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) );
			} );
		}

		if ( !arguments.length ) {
			return this.attr( "class", "" );
		}

		if ( typeof value === "string" && value ) {
			classes = value.match( rnotwhite ) || [];

			while ( ( elem = this[ i++ ] ) ) {
				curValue = getClass( elem );

				// This expression is here for better compressibility (see addClass)
				cur = elem.nodeType === 1 &&
					( " " + curValue + " " ).replace( rclass, " " );

				if ( cur ) {
					j = 0;
					while ( ( clazz = classes[ j++ ] ) ) {

						// Remove *all* instances
						while ( cur.indexOf( " " + clazz + " " ) > -1 ) {
							cur = cur.replace( " " + clazz + " ", " " );
						}
					}

					// Only assign if different to avoid unneeded rendering.
					finalValue = jQuery.trim( cur );
					if ( curValue !== finalValue ) {
						jQuery.attr( elem, "class", finalValue );
					}
				}
			}
		}

		return this;
	},

	toggleClass: function( value, stateVal ) {
		var type = typeof value;

		if ( typeof stateVal === "boolean" && type === "string" ) {
			return stateVal ? this.addClass( value ) : this.removeClass( value );
		}

		if ( jQuery.isFunction( value ) ) {
			return this.each( function( i ) {
				jQuery( this ).toggleClass(
					value.call( this, i, getClass( this ), stateVal ),
					stateVal
				);
			} );
		}

		return this.each( function() {
			var className, i, self, classNames;

			if ( type === "string" ) {

				// Toggle individual class names
				i = 0;
				self = jQuery( this );
				classNames = value.match( rnotwhite ) || [];

				while ( ( className = classNames[ i++ ] ) ) {

					// Check each className given, space separated list
					if ( self.hasClass( className ) ) {
						self.removeClass( className );
					} else {
						self.addClass( className );
					}
				}

			// Toggle whole class name
			} else if ( value === undefined || type === "boolean" ) {
				className = getClass( this );
				if ( className ) {

					// store className if set
					jQuery._data( this, "__className__", className );
				}

				// If the element has a class name or if we're passed "false",
				// then remove the whole classname (if there was one, the above saved it).
				// Otherwise bring back whatever was previously saved (if anything),
				// falling back to the empty string if nothing was stored.
				jQuery.attr( this, "class",
					className || value === false ?
					"" :
					jQuery._data( this, "__className__" ) || ""
				);
			}
		} );
	},

	hasClass: function( selector ) {
		var className, elem,
			i = 0;

		className = " " + selector + " ";
		while ( ( elem = this[ i++ ] ) ) {
			if ( elem.nodeType === 1 &&
				( " " + getClass( elem ) + " " ).replace( rclass, " " )
					.indexOf( className ) > -1
			) {
				return true;
			}
		}

		return false;
	}
} );




// Return jQuery for attributes-only inclusion


jQuery.each( ( "blur focus focusin focusout load resize scroll unload click dblclick " +
	"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
	"change select submit keydown keypress keyup error contextmenu" ).split( " " ),
	function( i, name ) {

	// Handle event binding
	jQuery.fn[ name ] = function( data, fn ) {
		return arguments.length > 0 ?
			this.on( name, null, data, fn ) :
			this.trigger( name );
	};
} );

jQuery.fn.extend( {
	hover: function( fnOver, fnOut ) {
		return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
	}
} );


var location = window.location;

var nonce = jQuery.now();

var rquery = ( /\?/ );



var rvalidtokens = /(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;

jQuery.parseJSON = function( data ) {

	// Attempt to parse using the native JSON parser first
	if ( window.JSON && window.JSON.parse ) {

		// Support: Android 2.3
		// Workaround failure to string-cast null input
		return window.JSON.parse( data + "" );
	}

	var requireNonComma,
		depth = null,
		str = jQuery.trim( data + "" );

	// Guard against invalid (and possibly dangerous) input by ensuring that nothing remains
	// after removing valid tokens
	return str && !jQuery.trim( str.replace( rvalidtokens, function( token, comma, open, close ) {

		// Force termination if we see a misplaced comma
		if ( requireNonComma && comma ) {
			depth = 0;
		}

		// Perform no more replacements after returning to outermost depth
		if ( depth === 0 ) {
			return token;
		}

		// Commas must not follow "[", "{", or ","
		requireNonComma = open || comma;

		// Determine new depth
		// array/object open ("[" or "{"): depth += true - false (increment)
		// array/object close ("]" or "}"): depth += false - true (decrement)
		// other cases ("," or primitive): depth += true - true (numeric cast)
		depth += !close - !open;

		// Remove this token
		return "";
	} ) ) ?
		( Function( "return " + str ) )() :
		jQuery.error( "Invalid JSON: " + data );
};


// Cross-browser xml parsing
jQuery.parseXML = function( data ) {
	var xml, tmp;
	if ( !data || typeof data !== "string" ) {
		return null;
	}
	try {
		if ( window.DOMParser ) { // Standard
			tmp = new window.DOMParser();
			xml = tmp.parseFromString( data, "text/xml" );
		} else { // IE
			xml = new window.ActiveXObject( "Microsoft.XMLDOM" );
			xml.async = "false";
			xml.loadXML( data );
		}
	} catch ( e ) {
		xml = undefined;
	}
	if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
		jQuery.error( "Invalid XML: " + data );
	}
	return xml;
};


var
	rhash = /#.*$/,
	rts = /([?&])_=[^&]*/,

	// IE leaves an \r character at EOL
	rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg,

	// #7653, #8125, #8152: local protocol detection
	rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
	rnoContent = /^(?:GET|HEAD)$/,
	rprotocol = /^\/\//,
	rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,

	/* Prefilters
	 * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
	 * 2) These are called:
	 *    - BEFORE asking for a transport
	 *    - AFTER param serialization (s.data is a string if s.processData is true)
	 * 3) key is the dataType
	 * 4) the catchall symbol "*" can be used
	 * 5) execution will start with transport dataType and THEN continue down to "*" if needed
	 */
	prefilters = {},

	/* Transports bindings
	 * 1) key is the dataType
	 * 2) the catchall symbol "*" can be used
	 * 3) selection will start with transport dataType and THEN go to "*" if needed
	 */
	transports = {},

	// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
	allTypes = "*/".concat( "*" ),

	// Document location
	ajaxLocation = location.href,

	// Segment location into parts
	ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];

// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {

	// dataTypeExpression is optional and defaults to "*"
	return function( dataTypeExpression, func ) {

		if ( typeof dataTypeExpression !== "string" ) {
			func = dataTypeExpression;
			dataTypeExpression = "*";
		}

		var dataType,
			i = 0,
			dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || [];

		if ( jQuery.isFunction( func ) ) {

			// For each dataType in the dataTypeExpression
			while ( ( dataType = dataTypes[ i++ ] ) ) {

				// Prepend if requested
				if ( dataType.charAt( 0 ) === "+" ) {
					dataType = dataType.slice( 1 ) || "*";
					( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func );

				// Otherwise append
				} else {
					( structure[ dataType ] = structure[ dataType ] || [] ).push( func );
				}
			}
		}
	};
}

// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {

	var inspected = {},
		seekingTransport = ( structure === transports );

	function inspect( dataType ) {
		var selected;
		inspected[ dataType ] = true;
		jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
			var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
			if ( typeof dataTypeOrTransport === "string" &&
				!seekingTransport && !inspected[ dataTypeOrTransport ] ) {

				options.dataTypes.unshift( dataTypeOrTransport );
				inspect( dataTypeOrTransport );
				return false;
			} else if ( seekingTransport ) {
				return !( selected = dataTypeOrTransport );
			}
		} );
		return selected;
	}

	return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
}

// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
	var deep, key,
		flatOptions = jQuery.ajaxSettings.flatOptions || {};

	for ( key in src ) {
		if ( src[ key ] !== undefined ) {
			( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
		}
	}
	if ( deep ) {
		jQuery.extend( true, target, deep );
	}

	return target;
}

/* Handles responses to an ajax request:
 * - finds the right dataType (mediates between content-type and expected dataType)
 * - returns the corresponding response
 */
function ajaxHandleResponses( s, jqXHR, responses ) {
	var firstDataType, ct, finalDataType, type,
		contents = s.contents,
		dataTypes = s.dataTypes;

	// Remove auto dataType and get content-type in the process
	while ( dataTypes[ 0 ] === "*" ) {
		dataTypes.shift();
		if ( ct === undefined ) {
			ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" );
		}
	}

	// Check if we're dealing with a known content-type
	if ( ct ) {
		for ( type in contents ) {
			if ( contents[ type ] && contents[ type ].test( ct ) ) {
				dataTypes.unshift( type );
				break;
			}
		}
	}

	// Check to see if we have a response for the expected dataType
	if ( dataTypes[ 0 ] in responses ) {
		finalDataType = dataTypes[ 0 ];
	} else {

		// Try convertible dataTypes
		for ( type in responses ) {
			if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) {
				finalDataType = type;
				break;
			}
			if ( !firstDataType ) {
				firstDataType = type;
			}
		}

		// Or just use first one
		finalDataType = finalDataType || firstDataType;
	}

	// If we found a dataType
	// We add the dataType to the list if needed
	// and return the corresponding response
	if ( finalDataType ) {
		if ( finalDataType !== dataTypes[ 0 ] ) {
			dataTypes.unshift( finalDataType );
		}
		return responses[ finalDataType ];
	}
}

/* Chain conversions given the request and the original response
 * Also sets the responseXXX fields on the jqXHR instance
 */
function ajaxConvert( s, response, jqXHR, isSuccess ) {
	var conv2, current, conv, tmp, prev,
		converters = {},

		// Work with a copy of dataTypes in case we need to modify it for conversion
		dataTypes = s.dataTypes.slice();

	// Create converters map with lowercased keys
	if ( dataTypes[ 1 ] ) {
		for ( conv in s.converters ) {
			converters[ conv.toLowerCase() ] = s.converters[ conv ];
		}
	}

	current = dataTypes.shift();

	// Convert to each sequential dataType
	while ( current ) {

		if ( s.responseFields[ current ] ) {
			jqXHR[ s.responseFields[ current ] ] = response;
		}

		// Apply the dataFilter if provided
		if ( !prev && isSuccess && s.dataFilter ) {
			response = s.dataFilter( response, s.dataType );
		}

		prev = current;
		current = dataTypes.shift();

		if ( current ) {

			// There's only work to do if current dataType is non-auto
			if ( current === "*" ) {

				current = prev;

			// Convert response if prev dataType is non-auto and differs from current
			} else if ( prev !== "*" && prev !== current ) {

				// Seek a direct converter
				conv = converters[ prev + " " + current ] || converters[ "* " + current ];

				// If none found, seek a pair
				if ( !conv ) {
					for ( conv2 in converters ) {

						// If conv2 outputs current
						tmp = conv2.split( " " );
						if ( tmp[ 1 ] === current ) {

							// If prev can be converted to accepted input
							conv = converters[ prev + " " + tmp[ 0 ] ] ||
								converters[ "* " + tmp[ 0 ] ];
							if ( conv ) {

								// Condense equivalence converters
								if ( conv === true ) {
									conv = converters[ conv2 ];

								// Otherwise, insert the intermediate dataType
								} else if ( converters[ conv2 ] !== true ) {
									current = tmp[ 0 ];
									dataTypes.unshift( tmp[ 1 ] );
								}
								break;
							}
						}
					}
				}

				// Apply converter (if not an equivalence)
				if ( conv !== true ) {

					// Unless errors are allowed to bubble, catch and return them
					if ( conv && s[ "throws" ] ) { // jscs:ignore requireDotNotation
						response = conv( response );
					} else {
						try {
							response = conv( response );
						} catch ( e ) {
							return {
								state: "parsererror",
								error: conv ? e : "No conversion from " + prev + " to " + current
							};
						}
					}
				}
			}
		}
	}

	return { state: "success", data: response };
}

jQuery.extend( {

	// Counter for holding the number of active queries
	active: 0,

	// Last-Modified header cache for next request
	lastModified: {},
	etag: {},

	ajaxSettings: {
		url: ajaxLocation,
		type: "GET",
		isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
		global: true,
		processData: true,
		async: true,
		contentType: "application/x-www-form-urlencoded; charset=UTF-8",
		/*
		timeout: 0,
		data: null,
		dataType: null,
		username: null,
		password: null,
		cache: null,
		throws: false,
		traditional: false,
		headers: {},
		*/

		accepts: {
			"*": allTypes,
			text: "text/plain",
			html: "text/html",
			xml: "application/xml, text/xml",
			json: "application/json, text/javascript"
		},

		contents: {
			xml: /\bxml\b/,
			html: /\bhtml/,
			json: /\bjson\b/
		},

		responseFields: {
			xml: "responseXML",
			text: "responseText",
			json: "responseJSON"
		},

		// Data converters
		// Keys separate source (or catchall "*") and destination types with a single space
		converters: {

			// Convert anything to text
			"* text": String,

			// Text to html (true = no transformation)
			"text html": true,

			// Evaluate text as a json expression
			"text json": jQuery.parseJSON,

			// Parse text as xml
			"text xml": jQuery.parseXML
		},

		// For options that shouldn't be deep extended:
		// you can add your own custom options here if
		// and when you create one that shouldn't be
		// deep extended (see ajaxExtend)
		flatOptions: {
			url: true,
			context: true
		}
	},

	// Creates a full fledged settings object into target
	// with both ajaxSettings and settings fields.
	// If target is omitted, writes into ajaxSettings.
	ajaxSetup: function( target, settings ) {
		return settings ?

			// Building a settings object
			ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :

			// Extending ajaxSettings
			ajaxExtend( jQuery.ajaxSettings, target );
	},

	ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
	ajaxTransport: addToPrefiltersOrTransports( transports ),

	// Main method
	ajax: function( url, options ) {

		// If url is an object, simulate pre-1.5 signature
		if ( typeof url === "object" ) {
			options = url;
			url = undefined;
		}

		// Force options to be an object
		options = options || {};

		var

			// Cross-domain detection vars
			parts,

			// Loop variable
			i,

			// URL without anti-cache param
			cacheURL,

			// Response headers as string
			responseHeadersString,

			// timeout handle
			timeoutTimer,

			// To know if global events are to be dispatched
			fireGlobals,

			transport,

			// Response headers
			responseHeaders,

			// Create the final options object
			s = jQuery.ajaxSetup( {}, options ),

			// Callbacks context
			callbackContext = s.context || s,

			// Context for global events is callbackContext if it is a DOM node or jQuery collection
			globalEventContext = s.context &&
				( callbackContext.nodeType || callbackContext.jquery ) ?
					jQuery( callbackContext ) :
					jQuery.event,

			// Deferreds
			deferred = jQuery.Deferred(),
			completeDeferred = jQuery.Callbacks( "once memory" ),

			// Status-dependent callbacks
			statusCode = s.statusCode || {},

			// Headers (they are sent all at once)
			requestHeaders = {},
			requestHeadersNames = {},

			// The jqXHR state
			state = 0,

			// Default abort message
			strAbort = "canceled",

			// Fake xhr
			jqXHR = {
				readyState: 0,

				// Builds headers hashtable if needed
				getResponseHeader: function( key ) {
					var match;
					if ( state === 2 ) {
						if ( !responseHeaders ) {
							responseHeaders = {};
							while ( ( match = rheaders.exec( responseHeadersString ) ) ) {
								responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ];
							}
						}
						match = responseHeaders[ key.toLowerCase() ];
					}
					return match == null ? null : match;
				},

				// Raw string
				getAllResponseHeaders: function() {
					return state === 2 ? responseHeadersString : null;
				},

				// Caches the header
				setRequestHeader: function( name, value ) {
					var lname = name.toLowerCase();
					if ( !state ) {
						name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
						requestHeaders[ name ] = value;
					}
					return this;
				},

				// Overrides response content-type header
				overrideMimeType: function( type ) {
					if ( !state ) {
						s.mimeType = type;
					}
					return this;
				},

				// Status-dependent callbacks
				statusCode: function( map ) {
					var code;
					if ( map ) {
						if ( state < 2 ) {
							for ( code in map ) {

								// Lazy-add the new callback in a way that preserves old ones
								statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
							}
						} else {

							// Execute the appropriate callbacks
							jqXHR.always( map[ jqXHR.status ] );
						}
					}
					return this;
				},

				// Cancel the request
				abort: function( statusText ) {
					var finalText = statusText || strAbort;
					if ( transport ) {
						transport.abort( finalText );
					}
					done( 0, finalText );
					return this;
				}
			};

		// Attach deferreds
		deferred.promise( jqXHR ).complete = completeDeferred.add;
		jqXHR.success = jqXHR.done;
		jqXHR.error = jqXHR.fail;

		// Remove hash character (#7531: and string promotion)
		// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
		// Handle falsy url in the settings object (#10093: consistency with old signature)
		// We also use the url parameter if available
		s.url = ( ( url || s.url || ajaxLocation ) + "" )
			.replace( rhash, "" )
			.replace( rprotocol, ajaxLocParts[ 1 ] + "//" );

		// Alias method option to type as per ticket #12004
		s.type = options.method || options.type || s.method || s.type;

		// Extract dataTypes list
		s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ];

		// A cross-domain request is in order when we have a protocol:host:port mismatch
		if ( s.crossDomain == null ) {
			parts = rurl.exec( s.url.toLowerCase() );
			s.crossDomain = !!( parts &&
				( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
					( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !==
						( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) )
			);
		}

		// Convert data if not already a string
		if ( s.data && s.processData && typeof s.data !== "string" ) {
			s.data = jQuery.param( s.data, s.traditional );
		}

		// Apply prefilters
		inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );

		// If request was aborted inside a prefilter, stop there
		if ( state === 2 ) {
			return jqXHR;
		}

		// We can fire global events as of now if asked to
		// Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118)
		fireGlobals = jQuery.event && s.global;

		// Watch for a new set of requests
		if ( fireGlobals && jQuery.active++ === 0 ) {
			jQuery.event.trigger( "ajaxStart" );
		}

		// Uppercase the type
		s.type = s.type.toUpperCase();

		// Determine if request has content
		s.hasContent = !rnoContent.test( s.type );

		// Save the URL in case we're toying with the If-Modified-Since
		// and/or If-None-Match header later on
		cacheURL = s.url;

		// More options handling for requests with no content
		if ( !s.hasContent ) {

			// If data is available, append data to url
			if ( s.data ) {
				cacheURL = ( s.url += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data );

				// #9682: remove data so that it's not used in an eventual retry
				delete s.data;
			}

			// Add anti-cache in url if needed
			if ( s.cache === false ) {
				s.url = rts.test( cacheURL ) ?

					// If there is already a '_' parameter, set its value
					cacheURL.replace( rts, "$1_=" + nonce++ ) :

					// Otherwise add one to the end
					cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++;
			}
		}

		// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
		if ( s.ifModified ) {
			if ( jQuery.lastModified[ cacheURL ] ) {
				jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
			}
			if ( jQuery.etag[ cacheURL ] ) {
				jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
			}
		}

		// Set the correct header, if data is being sent
		if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
			jqXHR.setRequestHeader( "Content-Type", s.contentType );
		}

		// Set the Accepts header for the server, depending on the dataType
		jqXHR.setRequestHeader(
			"Accept",
			s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ?
				s.accepts[ s.dataTypes[ 0 ] ] +
					( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
				s.accepts[ "*" ]
		);

		// Check for headers option
		for ( i in s.headers ) {
			jqXHR.setRequestHeader( i, s.headers[ i ] );
		}

		// Allow custom headers/mimetypes and early abort
		if ( s.beforeSend &&
			( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {

			// Abort if not done already and return
			return jqXHR.abort();
		}

		// aborting is no longer a cancellation
		strAbort = "abort";

		// Install callbacks on deferreds
		for ( i in { success: 1, error: 1, complete: 1 } ) {
			jqXHR[ i ]( s[ i ] );
		}

		// Get transport
		transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );

		// If no transport, we auto-abort
		if ( !transport ) {
			done( -1, "No Transport" );
		} else {
			jqXHR.readyState = 1;

			// Send global event
			if ( fireGlobals ) {
				globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
			}

			// If request was aborted inside ajaxSend, stop there
			if ( state === 2 ) {
				return jqXHR;
			}

			// Timeout
			if ( s.async && s.timeout > 0 ) {
				timeoutTimer = window.setTimeout( function() {
					jqXHR.abort( "timeout" );
				}, s.timeout );
			}

			try {
				state = 1;
				transport.send( requestHeaders, done );
			} catch ( e ) {

				// Propagate exception as error if not done
				if ( state < 2 ) {
					done( -1, e );

				// Simply rethrow otherwise
				} else {
					throw e;
				}
			}
		}

		// Callback for when everything is done
		function done( status, nativeStatusText, responses, headers ) {
			var isSuccess, success, error, response, modified,
				statusText = nativeStatusText;

			// Called once
			if ( state === 2 ) {
				return;
			}

			// State is "done" now
			state = 2;

			// Clear timeout if it exists
			if ( timeoutTimer ) {
				window.clearTimeout( timeoutTimer );
			}

			// Dereference transport for early garbage collection
			// (no matter how long the jqXHR object will be used)
			transport = undefined;

			// Cache response headers
			responseHeadersString = headers || "";

			// Set readyState
			jqXHR.readyState = status > 0 ? 4 : 0;

			// Determine if successful
			isSuccess = status >= 200 && status < 300 || status === 304;

			// Get response data
			if ( responses ) {
				response = ajaxHandleResponses( s, jqXHR, responses );
			}

			// Convert no matter what (that way responseXXX fields are always set)
			response = ajaxConvert( s, response, jqXHR, isSuccess );

			// If successful, handle type chaining
			if ( isSuccess ) {

				// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
				if ( s.ifModified ) {
					modified = jqXHR.getResponseHeader( "Last-Modified" );
					if ( modified ) {
						jQuery.lastModified[ cacheURL ] = modified;
					}
					modified = jqXHR.getResponseHeader( "etag" );
					if ( modified ) {
						jQuery.etag[ cacheURL ] = modified;
					}
				}

				// if no content
				if ( status === 204 || s.type === "HEAD" ) {
					statusText = "nocontent";

				// if not modified
				} else if ( status === 304 ) {
					statusText = "notmodified";

				// If we have data, let's convert it
				} else {
					statusText = response.state;
					success = response.data;
					error = response.error;
					isSuccess = !error;
				}
			} else {

				// We extract error from statusText
				// then normalize statusText and status for non-aborts
				error = statusText;
				if ( status || !statusText ) {
					statusText = "error";
					if ( status < 0 ) {
						status = 0;
					}
				}
			}

			// Set data for the fake xhr object
			jqXHR.status = status;
			jqXHR.statusText = ( nativeStatusText || statusText ) + "";

			// Success/Error
			if ( isSuccess ) {
				deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
			} else {
				deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
			}

			// Status-dependent callbacks
			jqXHR.statusCode( statusCode );
			statusCode = undefined;

			if ( fireGlobals ) {
				globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
					[ jqXHR, s, isSuccess ? success : error ] );
			}

			// Complete
			completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );

			if ( fireGlobals ) {
				globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );

				// Handle the global AJAX counter
				if ( !( --jQuery.active ) ) {
					jQuery.event.trigger( "ajaxStop" );
				}
			}
		}

		return jqXHR;
	},

	getJSON: function( url, data, callback ) {
		return jQuery.get( url, data, callback, "json" );
	},

	getScript: function( url, callback ) {
		return jQuery.get( url, undefined, callback, "script" );
	}
} );

jQuery.each( [ "get", "post" ], function( i, method ) {
	jQuery[ method ] = function( url, data, callback, type ) {

		// shift arguments if data argument was omitted
		if ( jQuery.isFunction( data ) ) {
			type = type || callback;
			callback = data;
			data = undefined;
		}

		// The url can be an options object (which then must have .url)
		return jQuery.ajax( jQuery.extend( {
			url: url,
			type: method,
			dataType: type,
			data: data,
			success: callback
		}, jQuery.isPlainObject( url ) && url ) );
	};
} );


jQuery._evalUrl = function( url ) {
	return jQuery.ajax( {
		url: url,

		// Make this explicit, since user can override this through ajaxSetup (#11264)
		type: "GET",
		dataType: "script",
		cache: true,
		async: false,
		global: false,
		"throws": true
	} );
};


jQuery.fn.extend( {
	wrapAll: function( html ) {
		if ( jQuery.isFunction( html ) ) {
			return this.each( function( i ) {
				jQuery( this ).wrapAll( html.call( this, i ) );
			} );
		}

		if ( this[ 0 ] ) {

			// The elements to wrap the target around
			var wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true );

			if ( this[ 0 ].parentNode ) {
				wrap.insertBefore( this[ 0 ] );
			}

			wrap.map( function() {
				var elem = this;

				while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
					elem = elem.firstChild;
				}

				return elem;
			} ).append( this );
		}

		return this;
	},

	wrapInner: function( html ) {
		if ( jQuery.isFunction( html ) ) {
			return this.each( function( i ) {
				jQuery( this ).wrapInner( html.call( this, i ) );
			} );
		}

		return this.each( function() {
			var self = jQuery( this ),
				contents = self.contents();

			if ( contents.length ) {
				contents.wrapAll( html );

			} else {
				self.append( html );
			}
		} );
	},

	wrap: function( html ) {
		var isFunction = jQuery.isFunction( html );

		return this.each( function( i ) {
			jQuery( this ).wrapAll( isFunction ? html.call( this, i ) : html );
		} );
	},

	unwrap: function() {
		return this.parent().each( function() {
			if ( !jQuery.nodeName( this, "body" ) ) {
				jQuery( this ).replaceWith( this.childNodes );
			}
		} ).end();
	}
} );


function getDisplay( elem ) {
	return elem.style && elem.style.display || jQuery.css( elem, "display" );
}

function filterHidden( elem ) {

	// Disconnected elements are considered hidden
	if ( !jQuery.contains( elem.ownerDocument || document, elem ) ) {
		return true;
	}
	while ( elem && elem.nodeType === 1 ) {
		if ( getDisplay( elem ) === "none" || elem.type === "hidden" ) {
			return true;
		}
		elem = elem.parentNode;
	}
	return false;
}

jQuery.expr.filters.hidden = function( elem ) {

	// Support: Opera <= 12.12
	// Opera reports offsetWidths and offsetHeights less than zero on some elements
	return support.reliableHiddenOffsets() ?
		( elem.offsetWidth <= 0 && elem.offsetHeight <= 0 &&
			!elem.getClientRects().length ) :
			filterHidden( elem );
};

jQuery.expr.filters.visible = function( elem ) {
	return !jQuery.expr.filters.hidden( elem );
};




var r20 = /%20/g,
	rbracket = /\[\]$/,
	rCRLF = /\r?\n/g,
	rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
	rsubmittable = /^(?:input|select|textarea|keygen)/i;

function buildParams( prefix, obj, traditional, add ) {
	var name;

	if ( jQuery.isArray( obj ) ) {

		// Serialize array item.
		jQuery.each( obj, function( i, v ) {
			if ( traditional || rbracket.test( prefix ) ) {

				// Treat each array item as a scalar.
				add( prefix, v );

			} else {

				// Item is non-scalar (array or object), encode its numeric index.
				buildParams(
					prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]",
					v,
					traditional,
					add
				);
			}
		} );

	} else if ( !traditional && jQuery.type( obj ) === "object" ) {

		// Serialize object item.
		for ( name in obj ) {
			buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
		}

	} else {

		// Serialize scalar item.
		add( prefix, obj );
	}
}

// Serialize an array of form elements or a set of
// key/values into a query string
jQuery.param = function( a, traditional ) {
	var prefix,
		s = [],
		add = function( key, value ) {

			// If value is a function, invoke it and return its value
			value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
			s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
		};

	// Set traditional to true for jQuery <= 1.3.2 behavior.
	if ( traditional === undefined ) {
		traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
	}

	// If an array was passed in, assume that it is an array of form elements.
	if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {

		// Serialize the form elements
		jQuery.each( a, function() {
			add( this.name, this.value );
		} );

	} else {

		// If traditional, encode the "old" way (the way 1.3.2 or older
		// did it), otherwise encode params recursively.
		for ( prefix in a ) {
			buildParams( prefix, a[ prefix ], traditional, add );
		}
	}

	// Return the resulting serialization
	return s.join( "&" ).replace( r20, "+" );
};

jQuery.fn.extend( {
	serialize: function() {
		return jQuery.param( this.serializeArray() );
	},
	serializeArray: function() {
		return this.map( function() {

			// Can add propHook for "elements" to filter or add form elements
			var elements = jQuery.prop( this, "elements" );
			return elements ? jQuery.makeArray( elements ) : this;
		} )
		.filter( function() {
			var type = this.type;

			// Use .is(":disabled") so that fieldset[disabled] works
			return this.name && !jQuery( this ).is( ":disabled" ) &&
				rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
				( this.checked || !rcheckableType.test( type ) );
		} )
		.map( function( i, elem ) {
			var val = jQuery( this ).val();

			return val == null ?
				null :
				jQuery.isArray( val ) ?
					jQuery.map( val, function( val ) {
						return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
					} ) :
					{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
		} ).get();
	}
} );


// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject !== undefined ?

	// Support: IE6-IE8
	function() {

		// XHR cannot access local files, always use ActiveX for that case
		if ( this.isLocal ) {
			return createActiveXHR();
		}

		// Support: IE 9-11
		// IE seems to error on cross-domain PATCH requests when ActiveX XHR
		// is used. In IE 9+ always use the native XHR.
		// Note: this condition won't catch Edge as it doesn't define
		// document.documentMode but it also doesn't support ActiveX so it won't
		// reach this code.
		if ( document.documentMode > 8 ) {
			return createStandardXHR();
		}

		// Support: IE<9
		// oldIE XHR does not support non-RFC2616 methods (#13240)
		// See http://msdn.microsoft.com/en-us/library/ie/ms536648(v=vs.85).aspx
		// and http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9
		// Although this check for six methods instead of eight
		// since IE also does not support "trace" and "connect"
		return /^(get|post|head|put|delete|options)$/i.test( this.type ) &&
			createStandardXHR() || createActiveXHR();
	} :

	// For all other browsers, use the standard XMLHttpRequest object
	createStandardXHR;

var xhrId = 0,
	xhrCallbacks = {},
	xhrSupported = jQuery.ajaxSettings.xhr();

// Support: IE<10
// Open requests must be manually aborted on unload (#5280)
// See https://support.microsoft.com/kb/2856746 for more info
if ( window.attachEvent ) {
	window.attachEvent( "onunload", function() {
		for ( var key in xhrCallbacks ) {
			xhrCallbacks[ key ]( undefined, true );
		}
	} );
}

// Determine support properties
support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
xhrSupported = support.ajax = !!xhrSupported;

// Create transport if the browser can provide an xhr
if ( xhrSupported ) {

	jQuery.ajaxTransport( function( options ) {

		// Cross domain only allowed if supported through XMLHttpRequest
		if ( !options.crossDomain || support.cors ) {

			var callback;

			return {
				send: function( headers, complete ) {
					var i,
						xhr = options.xhr(),
						id = ++xhrId;

					// Open the socket
					xhr.open(
						options.type,
						options.url,
						options.async,
						options.username,
						options.password
					);

					// Apply custom fields if provided
					if ( options.xhrFields ) {
						for ( i in options.xhrFields ) {
							xhr[ i ] = options.xhrFields[ i ];
						}
					}

					// Override mime type if needed
					if ( options.mimeType && xhr.overrideMimeType ) {
						xhr.overrideMimeType( options.mimeType );
					}

					// X-Requested-With header
					// For cross-domain requests, seeing as conditions for a preflight are
					// akin to a jigsaw puzzle, we simply never set it to be sure.
					// (it can always be set on a per-request basis or even using ajaxSetup)
					// For same-domain requests, won't change header if already provided.
					if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) {
						headers[ "X-Requested-With" ] = "XMLHttpRequest";
					}

					// Set headers
					for ( i in headers ) {

						// Support: IE<9
						// IE's ActiveXObject throws a 'Type Mismatch' exception when setting
						// request header to a null-value.
						//
						// To keep consistent with other XHR implementations, cast the value
						// to string and ignore `undefined`.
						if ( headers[ i ] !== undefined ) {
							xhr.setRequestHeader( i, headers[ i ] + "" );
						}
					}

					// Do send the request
					// This may raise an exception which is actually
					// handled in jQuery.ajax (so no try/catch here)
					xhr.send( ( options.hasContent && options.data ) || null );

					// Listener
					callback = function( _, isAbort ) {
						var status, statusText, responses;

						// Was never called and is aborted or complete
						if ( callback && ( isAbort || xhr.readyState === 4 ) ) {

							// Clean up
							delete xhrCallbacks[ id ];
							callback = undefined;
							xhr.onreadystatechange = jQuery.noop;

							// Abort manually if needed
							if ( isAbort ) {
								if ( xhr.readyState !== 4 ) {
									xhr.abort();
								}
							} else {
								responses = {};
								status = xhr.status;

								// Support: IE<10
								// Accessing binary-data responseText throws an exception
								// (#11426)
								if ( typeof xhr.responseText === "string" ) {
									responses.text = xhr.responseText;
								}

								// Firefox throws an exception when accessing
								// statusText for faulty cross-domain requests
								try {
									statusText = xhr.statusText;
								} catch ( e ) {

									// We normalize with Webkit giving an empty statusText
									statusText = "";
								}

								// Filter status for non standard behaviors

								// If the request is local and we have data: assume a success
								// (success with no data won't get notified, that's the best we
								// can do given current implementations)
								if ( !status && options.isLocal && !options.crossDomain ) {
									status = responses.text ? 200 : 404;

								// IE - #1450: sometimes returns 1223 when it should be 204
								} else if ( status === 1223 ) {
									status = 204;
								}
							}
						}

						// Call complete if needed
						if ( responses ) {
							complete( status, statusText, responses, xhr.getAllResponseHeaders() );
						}
					};

					// Do send the request
					// `xhr.send` may raise an exception, but it will be
					// handled in jQuery.ajax (so no try/catch here)
					if ( !options.async ) {

						// If we're in sync mode we fire the callback
						callback();
					} else if ( xhr.readyState === 4 ) {

						// (IE6 & IE7) if it's in cache and has been
						// retrieved directly we need to fire the callback
						window.setTimeout( callback );
					} else {

						// Register the callback, but delay it in case `xhr.send` throws
						// Add to the list of active xhr callbacks
						xhr.onreadystatechange = xhrCallbacks[ id ] = callback;
					}
				},

				abort: function() {
					if ( callback ) {
						callback( undefined, true );
					}
				}
			};
		}
	} );
}

// Functions to create xhrs
function createStandardXHR() {
	try {
		return new window.XMLHttpRequest();
	} catch ( e ) {}
}

function createActiveXHR() {
	try {
		return new window.ActiveXObject( "Microsoft.XMLHTTP" );
	} catch ( e ) {}
}




// Install script dataType
jQuery.ajaxSetup( {
	accepts: {
		script: "text/javascript, application/javascript, " +
			"application/ecmascript, application/x-ecmascript"
	},
	contents: {
		script: /\b(?:java|ecma)script\b/
	},
	converters: {
		"text script": function( text ) {
			jQuery.globalEval( text );
			return text;
		}
	}
} );

// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
	if ( s.cache === undefined ) {
		s.cache = false;
	}
	if ( s.crossDomain ) {
		s.type = "GET";
		s.global = false;
	}
} );

// Bind script tag hack transport
jQuery.ajaxTransport( "script", function( s ) {

	// This transport only deals with cross domain requests
	if ( s.crossDomain ) {

		var script,
			head = document.head || jQuery( "head" )[ 0 ] || document.documentElement;

		return {

			send: function( _, callback ) {

				script = document.createElement( "script" );

				script.async = true;

				if ( s.scriptCharset ) {
					script.charset = s.scriptCharset;
				}

				script.src = s.url;

				// Attach handlers for all browsers
				script.onload = script.onreadystatechange = function( _, isAbort ) {

					if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {

						// Handle memory leak in IE
						script.onload = script.onreadystatechange = null;

						// Remove the script
						if ( script.parentNode ) {
							script.parentNode.removeChild( script );
						}

						// Dereference the script
						script = null;

						// Callback if not abort
						if ( !isAbort ) {
							callback( 200, "success" );
						}
					}
				};

				// Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending
				// Use native DOM manipulation to avoid our domManip AJAX trickery
				head.insertBefore( script, head.firstChild );
			},

			abort: function() {
				if ( script ) {
					script.onload( undefined, true );
				}
			}
		};
	}
} );




var oldCallbacks = [],
	rjsonp = /(=)\?(?=&|$)|\?\?/;

// Default jsonp settings
jQuery.ajaxSetup( {
	jsonp: "callback",
	jsonpCallback: function() {
		var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );
		this[ callback ] = true;
		return callback;
	}
} );

// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {

	var callbackName, overwritten, responseContainer,
		jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
			"url" :
			typeof s.data === "string" &&
				( s.contentType || "" )
					.indexOf( "application/x-www-form-urlencoded" ) === 0 &&
				rjsonp.test( s.data ) && "data"
		);

	// Handle iff the expected data type is "jsonp" or we have a parameter to set
	if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {

		// Get callback name, remembering preexisting value associated with it
		callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
			s.jsonpCallback() :
			s.jsonpCallback;

		// Insert callback into url or form data
		if ( jsonProp ) {
			s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
		} else if ( s.jsonp !== false ) {
			s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
		}

		// Use data converter to retrieve json after script execution
		s.converters[ "script json" ] = function() {
			if ( !responseContainer ) {
				jQuery.error( callbackName + " was not called" );
			}
			return responseContainer[ 0 ];
		};

		// force json dataType
		s.dataTypes[ 0 ] = "json";

		// Install callback
		overwritten = window[ callbackName ];
		window[ callbackName ] = function() {
			responseContainer = arguments;
		};

		// Clean-up function (fires after converters)
		jqXHR.always( function() {

			// If previous value didn't exist - remove it
			if ( overwritten === undefined ) {
				jQuery( window ).removeProp( callbackName );

			// Otherwise restore preexisting value
			} else {
				window[ callbackName ] = overwritten;
			}

			// Save back as free
			if ( s[ callbackName ] ) {

				// make sure that re-using the options doesn't screw things around
				s.jsonpCallback = originalSettings.jsonpCallback;

				// save the callback name for future use
				oldCallbacks.push( callbackName );
			}

			// Call if it was a function and we have a response
			if ( responseContainer && jQuery.isFunction( overwritten ) ) {
				overwritten( responseContainer[ 0 ] );
			}

			responseContainer = overwritten = undefined;
		} );

		// Delegate to script
		return "script";
	}
} );




// data: string of html
// context (optional): If specified, the fragment will be created in this context,
// defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
jQuery.parseHTML = function( data, context, keepScripts ) {
	if ( !data || typeof data !== "string" ) {
		return null;
	}
	if ( typeof context === "boolean" ) {
		keepScripts = context;
		context = false;
	}
	context = context || document;

	var parsed = rsingleTag.exec( data ),
		scripts = !keepScripts && [];

	// Single tag
	if ( parsed ) {
		return [ context.createElement( parsed[ 1 ] ) ];
	}

	parsed = buildFragment( [ data ], context, scripts );

	if ( scripts && scripts.length ) {
		jQuery( scripts ).remove();
	}

	return jQuery.merge( [], parsed.childNodes );
};


// Keep a copy of the old load method
var _load = jQuery.fn.load;

/**
 * Load a url into a page
 */
jQuery.fn.load = function( url, params, callback ) {
	if ( typeof url !== "string" && _load ) {
		return _load.apply( this, arguments );
	}

	var selector, type, response,
		self = this,
		off = url.indexOf( " " );

	if ( off > -1 ) {
		selector = jQuery.trim( url.slice( off, url.length ) );
		url = url.slice( 0, off );
	}

	// If it's a function
	if ( jQuery.isFunction( params ) ) {

		// We assume that it's the callback
		callback = params;
		params = undefined;

	// Otherwise, build a param string
	} else if ( params && typeof params === "object" ) {
		type = "POST";
	}

	// If we have elements to modify, make the request
	if ( self.length > 0 ) {
		jQuery.ajax( {
			url: url,

			// If "type" variable is undefined, then "GET" method will be used.
			// Make value of this field explicit since
			// user can override it through ajaxSetup method
			type: type || "GET",
			dataType: "html",
			data: params
		} ).done( function( responseText ) {

			// Save response for use in complete callback
			response = arguments;

			self.html( selector ?

				// If a selector was specified, locate the right elements in a dummy div
				// Exclude scripts to avoid IE 'Permission Denied' errors
				jQuery( "<div>" ).append( jQuery.parseHTML( responseText ) ).find( selector ) :

				// Otherwise use the full result
				responseText );

		// If the request succeeds, this function gets "data", "status", "jqXHR"
		// but they are ignored because response was set above.
		// If it fails, this function gets "jqXHR", "status", "error"
		} ).always( callback && function( jqXHR, status ) {
			self.each( function() {
				callback.apply( this, response || [ jqXHR.responseText, status, jqXHR ] );
			} );
		} );
	}

	return this;
};




// Attach a bunch of functions for handling common AJAX events
jQuery.each( [
	"ajaxStart",
	"ajaxStop",
	"ajaxComplete",
	"ajaxError",
	"ajaxSuccess",
	"ajaxSend"
], function( i, type ) {
	jQuery.fn[ type ] = function( fn ) {
		return this.on( type, fn );
	};
} );




jQuery.expr.filters.animated = function( elem ) {
	return jQuery.grep( jQuery.timers, function( fn ) {
		return elem === fn.elem;
	} ).length;
};





/**
 * Gets a window from an element
 */
function getWindow( elem ) {
	return jQuery.isWindow( elem ) ?
		elem :
		elem.nodeType === 9 ?
			elem.defaultView || elem.parentWindow :
			false;
}

jQuery.offset = {
	setOffset: function( elem, options, i ) {
		var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
			position = jQuery.css( elem, "position" ),
			curElem = jQuery( elem ),
			props = {};

		// set position first, in-case top/left are set even on static elem
		if ( position === "static" ) {
			elem.style.position = "relative";
		}

		curOffset = curElem.offset();
		curCSSTop = jQuery.css( elem, "top" );
		curCSSLeft = jQuery.css( elem, "left" );
		calculatePosition = ( position === "absolute" || position === "fixed" ) &&
			jQuery.inArray( "auto", [ curCSSTop, curCSSLeft ] ) > -1;

		// need to be able to calculate position if either top or left
		// is auto and position is either absolute or fixed
		if ( calculatePosition ) {
			curPosition = curElem.position();
			curTop = curPosition.top;
			curLeft = curPosition.left;
		} else {
			curTop = parseFloat( curCSSTop ) || 0;
			curLeft = parseFloat( curCSSLeft ) || 0;
		}

		if ( jQuery.isFunction( options ) ) {

			// Use jQuery.extend here to allow modification of coordinates argument (gh-1848)
			options = options.call( elem, i, jQuery.extend( {}, curOffset ) );
		}

		if ( options.top != null ) {
			props.top = ( options.top - curOffset.top ) + curTop;
		}
		if ( options.left != null ) {
			props.left = ( options.left - curOffset.left ) + curLeft;
		}

		if ( "using" in options ) {
			options.using.call( elem, props );
		} else {
			curElem.css( props );
		}
	}
};

jQuery.fn.extend( {
	offset: function( options ) {
		if ( arguments.length ) {
			return options === undefined ?
				this :
				this.each( function( i ) {
					jQuery.offset.setOffset( this, options, i );
				} );
		}

		var docElem, win,
			box = { top: 0, left: 0 },
			elem = this[ 0 ],
			doc = elem && elem.ownerDocument;

		if ( !doc ) {
			return;
		}

		docElem = doc.documentElement;

		// Make sure it's not a disconnected DOM node
		if ( !jQuery.contains( docElem, elem ) ) {
			return box;
		}

		// If we don't have gBCR, just use 0,0 rather than error
		// BlackBerry 5, iOS 3 (original iPhone)
		if ( typeof elem.getBoundingClientRect !== "undefined" ) {
			box = elem.getBoundingClientRect();
		}
		win = getWindow( doc );
		return {
			top: box.top  + ( win.pageYOffset || docElem.scrollTop )  - ( docElem.clientTop  || 0 ),
			left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 )
		};
	},

	position: function() {
		if ( !this[ 0 ] ) {
			return;
		}

		var offsetParent, offset,
			parentOffset = { top: 0, left: 0 },
			elem = this[ 0 ];

		// Fixed elements are offset from window (parentOffset = {top:0, left: 0},
		// because it is its only offset parent
		if ( jQuery.css( elem, "position" ) === "fixed" ) {

			// we assume that getBoundingClientRect is available when computed position is fixed
			offset = elem.getBoundingClientRect();
		} else {

			// Get *real* offsetParent
			offsetParent = this.offsetParent();

			// Get correct offsets
			offset = this.offset();
			if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
				parentOffset = offsetParent.offset();
			}

			// Add offsetParent borders
			parentOffset.top  += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true );
			parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true );
		}

		// Subtract parent offsets and element margins
		// note: when an element has margin: auto the offsetLeft and marginLeft
		// are the same in Safari causing offset.left to incorrectly be 0
		return {
			top:  offset.top  - parentOffset.top - jQuery.css( elem, "marginTop", true ),
			left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true )
		};
	},

	offsetParent: function() {
		return this.map( function() {
			var offsetParent = this.offsetParent;

			while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) &&
				jQuery.css( offsetParent, "position" ) === "static" ) ) {
				offsetParent = offsetParent.offsetParent;
			}
			return offsetParent || documentElement;
		} );
	}
} );

// Create scrollLeft and scrollTop methods
jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) {
	var top = /Y/.test( prop );

	jQuery.fn[ method ] = function( val ) {
		return access( this, function( elem, method, val ) {
			var win = getWindow( elem );

			if ( val === undefined ) {
				return win ? ( prop in win ) ? win[ prop ] :
					win.document.documentElement[ method ] :
					elem[ method ];
			}

			if ( win ) {
				win.scrollTo(
					!top ? val : jQuery( win ).scrollLeft(),
					top ? val : jQuery( win ).scrollTop()
				);

			} else {
				elem[ method ] = val;
			}
		}, method, val, arguments.length, null );
	};
} );

// Support: Safari<7-8+, Chrome<37-44+
// Add the top/left cssHooks using jQuery.fn.position
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// getComputedStyle returns percent when specified for top/left/bottom/right
// rather than make the css module depend on the offset module, we just check for it here
jQuery.each( [ "top", "left" ], function( i, prop ) {
	jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition,
		function( elem, computed ) {
			if ( computed ) {
				computed = curCSS( elem, prop );

				// if curCSS returns percentage, fallback to offset
				return rnumnonpx.test( computed ) ?
					jQuery( elem ).position()[ prop ] + "px" :
					computed;
			}
		}
	);
} );


// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
	jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name },
	function( defaultExtra, funcName ) {

		// margin is only for outerHeight, outerWidth
		jQuery.fn[ funcName ] = function( margin, value ) {
			var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
				extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );

			return access( this, function( elem, type, value ) {
				var doc;

				if ( jQuery.isWindow( elem ) ) {

					// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
					// isn't a whole lot we can do. See pull request at this URL for discussion:
					// https://github.com/jquery/jquery/pull/764
					return elem.document.documentElement[ "client" + name ];
				}

				// Get document width or height
				if ( elem.nodeType === 9 ) {
					doc = elem.documentElement;

					// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height],
					// whichever is greatest
					// unfortunately, this causes bug #3838 in IE6/8 only,
					// but there is currently no good, small way to fix it.
					return Math.max(
						elem.body[ "scroll" + name ], doc[ "scroll" + name ],
						elem.body[ "offset" + name ], doc[ "offset" + name ],
						doc[ "client" + name ]
					);
				}

				return value === undefined ?

					// Get width or height on the element, requesting but not forcing parseFloat
					jQuery.css( elem, type, extra ) :

					// Set width or height on the element
					jQuery.style( elem, type, value, extra );
			}, type, chainable ? margin : undefined, chainable, null );
		};
	} );
} );


jQuery.fn.extend( {

	bind: function( types, data, fn ) {
		return this.on( types, null, data, fn );
	},
	unbind: function( types, fn ) {
		return this.off( types, null, fn );
	},

	delegate: function( selector, types, data, fn ) {
		return this.on( types, selector, data, fn );
	},
	undelegate: function( selector, types, fn ) {

		// ( namespace ) or ( selector, types [, fn] )
		return arguments.length === 1 ?
			this.off( selector, "**" ) :
			this.off( types, selector || "**", fn );
	}
} );

// The number of elements contained in the matched element set
jQuery.fn.size = function() {
	return this.length;
};

jQuery.fn.andSelf = jQuery.fn.addBack;




// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.

// Note that for maximum portability, libraries that are not jQuery should
// declare themselves as anonymous modules, and avoid setting a global if an
// AMD loader is present. jQuery is a special case. For more information, see
// https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon

if ( typeof define === "function" && define.amd ) {
	define( "jquery", [], function() {
		return jQuery;
	} );
}



var

	// Map over jQuery in case of overwrite
	_jQuery = window.jQuery,

	// Map over the $ in case of overwrite
	_$ = window.$;

jQuery.noConflict = function( deep ) {
	if ( window.$ === jQuery ) {
		window.$ = _$;
	}

	if ( deep && window.jQuery === jQuery ) {
		window.jQuery = _jQuery;
	}

	return jQuery;
};

// Expose jQuery and $ identifiers, even in
// AMD (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
// and CommonJS for browser emulators (#13566)
if ( !noGlobal ) {
	window.jQuery = window.$ = jQuery;
}

return jQuery;
}));
;
/*! jQuery v2.2.4 | (c) jQuery Foundation | jquery.org/license */
!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=a.document,e=c.slice,f=c.concat,g=c.push,h=c.indexOf,i={},j=i.toString,k=i.hasOwnProperty,l={},m="2.2.4",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,selector:"",length:0,toArray:function(){return e.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:e.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a){return n.each(this,a)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(e.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor()},push:g,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(a=arguments[h]))for(b in a)c=g[b],d=a[b],g!==d&&(j&&d&&(n.isPlainObject(d)||(e=n.isArray(d)))?(e?(e=!1,f=c&&n.isArray(c)?c:[]):f=c&&n.isPlainObject(c)?c:{},g[b]=n.extend(j,f,d)):void 0!==d&&(g[b]=d));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray,isWindow:function(a){return null!=a&&a===a.window},isNumeric:function(a){var b=a&&a.toString();return!n.isArray(a)&&b-parseFloat(b)+1>=0},isPlainObject:function(a){var b;if("object"!==n.type(a)||a.nodeType||n.isWindow(a))return!1;if(a.constructor&&!k.call(a,"constructor")&&!k.call(a.constructor.prototype||{},"isPrototypeOf"))return!1;for(b in a);return void 0===b||k.call(a,b)},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?i[j.call(a)]||"object":typeof a},globalEval:function(a){var b,c=eval;a=n.trim(a),a&&(1===a.indexOf("use strict")?(b=d.createElement("script"),b.text=a,d.head.appendChild(b).parentNode.removeChild(b)):c(a))},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b){var c,d=0;if(s(a)){for(c=a.length;c>d;d++)if(b.call(a[d],d,a[d])===!1)break}else for(d in a)if(b.call(a[d],d,a[d])===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):g.call(c,a)),c},inArray:function(a,b,c){return null==b?-1:h.call(b,a,c)},merge:function(a,b){for(var c=+b.length,d=0,e=a.length;c>d;d++)a[e++]=b[d];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,e,g=0,h=[];if(s(a))for(d=a.length;d>g;g++)e=b(a[g],g,c),null!=e&&h.push(e);else for(g in a)e=b(a[g],g,c),null!=e&&h.push(e);return f.apply([],h)},guid:1,proxy:function(a,b){var c,d,f;return"string"==typeof b&&(c=a[b],b=a,a=c),n.isFunction(a)?(d=e.call(arguments,2),f=function(){return a.apply(b||this,d.concat(e.call(arguments)))},f.guid=a.guid=a.guid||n.guid++,f):void 0},now:Date.now,support:l}),"function"==typeof Symbol&&(n.fn[Symbol.iterator]=c[Symbol.iterator]),n.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(a,b){i["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=!!a&&"length"in a&&a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ga(),z=ga(),A=ga(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+M+"))|)"+L+"*\\]",O=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+N+")*)|.*)\\)|)",P=new RegExp(L+"+","g"),Q=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),R=new RegExp("^"+L+"*,"+L+"*"),S=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),T=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),U=new RegExp(O),V=new RegExp("^"+M+"$"),W={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M+"|[*])"),ATTR:new RegExp("^"+N),PSEUDO:new RegExp("^"+O),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},X=/^(?:input|select|textarea|button)$/i,Y=/^h\d$/i,Z=/^[^{]+\{\s*\[native \w/,$=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,_=/[+~]/,aa=/'|\\/g,ba=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),ca=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},da=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(ea){H={apply:E.length?function(a,b){G.apply(a,I.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fa(a,b,d,e){var f,h,j,k,l,o,r,s,w=b&&b.ownerDocument,x=b?b.nodeType:9;if(d=d||[],"string"!=typeof a||!a||1!==x&&9!==x&&11!==x)return d;if(!e&&((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,p)){if(11!==x&&(o=$.exec(a)))if(f=o[1]){if(9===x){if(!(j=b.getElementById(f)))return d;if(j.id===f)return d.push(j),d}else if(w&&(j=w.getElementById(f))&&t(b,j)&&j.id===f)return d.push(j),d}else{if(o[2])return H.apply(d,b.getElementsByTagName(a)),d;if((f=o[3])&&c.getElementsByClassName&&b.getElementsByClassName)return H.apply(d,b.getElementsByClassName(f)),d}if(c.qsa&&!A[a+" "]&&(!q||!q.test(a))){if(1!==x)w=b,s=a;else if("object"!==b.nodeName.toLowerCase()){(k=b.getAttribute("id"))?k=k.replace(aa,"\\$&"):b.setAttribute("id",k=u),r=g(a),h=r.length,l=V.test(k)?"#"+k:"[id='"+k+"']";while(h--)r[h]=l+" "+qa(r[h]);s=r.join(","),w=_.test(a)&&oa(b.parentNode)||b}if(s)try{return H.apply(d,w.querySelectorAll(s)),d}catch(y){}finally{k===u&&b.removeAttribute("id")}}}return i(a.replace(Q,"$1"),b,d,e)}function ga(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ha(a){return a[u]=!0,a}function ia(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ja(a,b){var c=a.split("|"),e=c.length;while(e--)d.attrHandle[c[e]]=b}function ka(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||C)-(~a.sourceIndex||C);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function la(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function na(a){return ha(function(b){return b=+b,ha(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function oa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=fa.support={},f=fa.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fa.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=n.documentElement,p=!f(n),(e=n.defaultView)&&e.top!==e&&(e.addEventListener?e.addEventListener("unload",da,!1):e.attachEvent&&e.attachEvent("onunload",da)),c.attributes=ia(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ia(function(a){return a.appendChild(n.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Z.test(n.getElementsByClassName),c.getById=ia(function(a){return o.appendChild(a).id=u,!n.getElementsByName||!n.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ba,ca);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ba,ca);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return"undefined"!=typeof b.getElementsByClassName&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=Z.test(n.querySelectorAll))&&(ia(function(a){o.appendChild(a).innerHTML="<a id='"+u+"'></a><select id='"+u+"-\r\\' msallowcapture=''><option selected=''></option></select>",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ia(function(a){var b=n.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+L+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=Z.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ia(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",O)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=Z.test(o.compareDocumentPosition),t=b||Z.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===n||a.ownerDocument===v&&t(v,a)?-1:b===n||b.ownerDocument===v&&t(v,b)?1:k?J(k,a)-J(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,g=[a],h=[b];if(!e||!f)return a===n?-1:b===n?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return ka(a,b);c=a;while(c=c.parentNode)g.unshift(c);c=b;while(c=c.parentNode)h.unshift(c);while(g[d]===h[d])d++;return d?ka(g[d],h[d]):g[d]===v?-1:h[d]===v?1:0},n):n},fa.matches=function(a,b){return fa(a,null,null,b)},fa.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(T,"='$1']"),c.matchesSelector&&p&&!A[b+" "]&&(!r||!r.test(b))&&(!q||!q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return fa(b,n,null,[a]).length>0},fa.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fa.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},fa.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fa.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=fa.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=fa.selectors={cacheLength:50,createPseudo:ha,match:W,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ba,ca),a[3]=(a[3]||a[4]||a[5]||"").replace(ba,ca),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||fa.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&fa.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return W.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&U.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ba,ca).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+L+")"+a+"("+L+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fa.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(P," ")+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h,t=!1;if(q){if(f){while(p){m=b;while(m=m[p])if(h?m.nodeName.toLowerCase()===r:1===m.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){m=q,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n&&j[2],m=n&&q.childNodes[n];while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if(1===m.nodeType&&++t&&m===b){k[a]=[w,n,t];break}}else if(s&&(m=b,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n),t===!1)while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if((h?m.nodeName.toLowerCase()===r:1===m.nodeType)&&++t&&(s&&(l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),k[a]=[w,t]),m===b))break;return t-=e,t===d||t%d===0&&t/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fa.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ha(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ha(function(a){var b=[],c=[],d=h(a.replace(Q,"$1"));return d[u]?ha(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ha(function(a){return function(b){return fa(a,b).length>0}}),contains:ha(function(a){return a=a.replace(ba,ca),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ha(function(a){return V.test(a||"")||fa.error("unsupported lang: "+a),a=a.replace(ba,ca).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Y.test(a.nodeName)},input:function(a){return X.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:na(function(){return[0]}),last:na(function(a,b){return[b-1]}),eq:na(function(a,b,c){return[0>c?c+b:c]}),even:na(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:na(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:na(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:na(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=la(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=ma(b);function pa(){}pa.prototype=d.filters=d.pseudos,d.setFilters=new pa,g=fa.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){c&&!(e=R.exec(h))||(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=S.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(Q," ")}),h=h.slice(c.length));for(g in d.filter)!(e=W[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?fa.error(a):z(a,i).slice(0)};function qa(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function ra(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j,k=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(j=b[u]||(b[u]={}),i=j[b.uniqueID]||(j[b.uniqueID]={}),(h=i[d])&&h[0]===w&&h[1]===f)return k[2]=h[2];if(i[d]=k,k[2]=a(b,c,g))return!0}}}function sa(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function ta(a,b,c){for(var d=0,e=b.length;e>d;d++)fa(a,b[d],c);return c}function ua(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(c&&!c(f,d,e)||(g.push(f),j&&b.push(h)));return g}function va(a,b,c,d,e,f){return d&&!d[u]&&(d=va(d)),e&&!e[u]&&(e=va(e,f)),ha(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ta(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ua(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ua(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?J(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ua(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function wa(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=ra(function(a){return a===b},h,!0),l=ra(function(a){return J(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];f>i;i++)if(c=d.relative[a[i].type])m=[ra(sa(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return va(i>1&&sa(m),i>1&&qa(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(Q,"$1"),c,e>i&&wa(a.slice(i,e)),f>e&&wa(a=a.slice(e)),f>e&&qa(a))}m.push(c)}return sa(m)}function xa(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,o,q,r=0,s="0",t=f&&[],u=[],v=j,x=f||e&&d.find.TAG("*",k),y=w+=null==v?1:Math.random()||.1,z=x.length;for(k&&(j=g===n||g||k);s!==z&&null!=(l=x[s]);s++){if(e&&l){o=0,g||l.ownerDocument===n||(m(l),h=!p);while(q=a[o++])if(q(l,g||n,h)){i.push(l);break}k&&(w=y)}c&&((l=!q&&l)&&r--,f&&t.push(l))}if(r+=s,c&&s!==r){o=0;while(q=b[o++])q(t,u,g,h);if(f){if(r>0)while(s--)t[s]||u[s]||(u[s]=F.call(i));u=ua(u)}H.apply(i,u),k&&!f&&u.length>0&&r+b.length>1&&fa.uniqueSort(i)}return k&&(w=y,j=v),t};return c?ha(f):f}return h=fa.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wa(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xa(e,d)),f.selector=a}return f},i=fa.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(ba,ca),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=W.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(ba,ca),_.test(j[0].type)&&oa(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qa(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,!b||_.test(a)&&oa(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ia(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ia(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||ja("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ia(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ja("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ia(function(a){return null==a.getAttribute("disabled")})||ja(K,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fa}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.uniqueSort=n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&n(a).is(c))break;d.push(a)}return d},v=function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c},w=n.expr.match.needsContext,x=/^<([\w-]+)\s*\/?>(?:<\/\1>|)$/,y=/^.[^:#\[\.,]*$/;function z(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(y.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return h.call(b,a)>-1!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=this.length,d=[],e=this;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;c>b;b++)if(n.contains(e[b],this))return!0}));for(b=0;c>b;b++)n.find(a,e[b],d);return d=this.pushStack(c>1?n.unique(d):d),d.selector=this.selector?this.selector+" "+a:a,d},filter:function(a){return this.pushStack(z(this,a||[],!1))},not:function(a){return this.pushStack(z(this,a||[],!0))},is:function(a){return!!z(this,"string"==typeof a&&w.test(a)?n(a):a||[],!1).length}});var A,B=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=n.fn.init=function(a,b,c){var e,f;if(!a)return this;if(c=c||A,"string"==typeof a){if(e="<"===a[0]&&">"===a[a.length-1]&&a.length>=3?[null,a,null]:B.exec(a),!e||!e[1]&&b)return!b||b.jquery?(b||c).find(a):this.constructor(b).find(a);if(e[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(e[1],b&&b.nodeType?b.ownerDocument||b:d,!0)),x.test(e[1])&&n.isPlainObject(b))for(e in b)n.isFunction(this[e])?this[e](b[e]):this.attr(e,b[e]);return this}return f=d.getElementById(e[2]),f&&f.parentNode&&(this.length=1,this[0]=f),this.context=d,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?void 0!==c.ready?c.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};C.prototype=n.fn,A=n(d);var D=/^(?:parents|prev(?:Until|All))/,E={children:!0,contents:!0,next:!0,prev:!0};n.fn.extend({has:function(a){var b=n(a,this),c=b.length;return this.filter(function(){for(var a=0;c>a;a++)if(n.contains(this,b[a]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=w.test(a)||"string"!=typeof a?n(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.uniqueSort(f):f)},index:function(a){return a?"string"==typeof a?h.call(n(a),this[0]):h.call(this,a.jquery?a[0]:a):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.uniqueSort(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function F(a,b){while((a=a[b])&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return u(a,"parentNode")},parentsUntil:function(a,b,c){return u(a,"parentNode",c)},next:function(a){return F(a,"nextSibling")},prev:function(a){return F(a,"previousSibling")},nextAll:function(a){return u(a,"nextSibling")},prevAll:function(a){return u(a,"previousSibling")},nextUntil:function(a,b,c){return u(a,"nextSibling",c)},prevUntil:function(a,b,c){return u(a,"previousSibling",c)},siblings:function(a){return v((a.parentNode||{}).firstChild,a)},children:function(a){return v(a.firstChild)},contents:function(a){return a.contentDocument||n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(E[a]||n.uniqueSort(e),D.test(a)&&e.reverse()),this.pushStack(e)}});var G=/\S+/g;function H(a){var b={};return n.each(a.match(G)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?H(a):n.extend({},a);var b,c,d,e,f=[],g=[],h=-1,i=function(){for(e=a.once,d=b=!0;g.length;h=-1){c=g.shift();while(++h<f.length)f[h].apply(c[0],c[1])===!1&&a.stopOnFalse&&(h=f.length,c=!1)}a.memory||(c=!1),b=!1,e&&(f=c?[]:"")},j={add:function(){return f&&(c&&!b&&(h=f.length-1,g.push(c)),function d(b){n.each(b,function(b,c){n.isFunction(c)?a.unique&&j.has(c)||f.push(c):c&&c.length&&"string"!==n.type(c)&&d(c)})}(arguments),c&&!b&&i()),this},remove:function(){return n.each(arguments,function(a,b){var c;while((c=n.inArray(b,f,c))>-1)f.splice(c,1),h>=c&&h--}),this},has:function(a){return a?n.inArray(a,f)>-1:f.length>0},empty:function(){return f&&(f=[]),this},disable:function(){return e=g=[],f=c="",this},disabled:function(){return!f},lock:function(){return e=g=[],c||(f=c=""),this},locked:function(){return!!e},fireWith:function(a,c){return e||(c=c||[],c=[a,c.slice?c.slice():c],g.push(c),b||i()),this},fire:function(){return j.fireWith(this,arguments),this},fired:function(){return!!d}};return j},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().progress(c.notify).done(c.resolve).fail(c.reject):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=e.call(arguments),d=c.length,f=1!==d||a&&n.isFunction(a.promise)?d:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(d){b[a]=this,c[a]=arguments.length>1?e.call(arguments):d,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(d>1)for(i=new Array(d),j=new Array(d),k=new Array(d);d>b;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().progress(h(b,j,i)).done(h(b,k,c)).fail(g.reject):--f;return f||g.resolveWith(k,c),g.promise()}});var I;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){(a===!0?--n.readyWait:n.isReady)||(n.isReady=!0,a!==!0&&--n.readyWait>0||(I.resolveWith(d,[n]),n.fn.triggerHandler&&(n(d).triggerHandler("ready"),n(d).off("ready"))))}});function J(){d.removeEventListener("DOMContentLoaded",J),a.removeEventListener("load",J),n.ready()}n.ready.promise=function(b){return I||(I=n.Deferred(),"complete"===d.readyState||"loading"!==d.readyState&&!d.documentElement.doScroll?a.setTimeout(n.ready):(d.addEventListener("DOMContentLoaded",J),a.addEventListener("load",J))),I.promise(b)},n.ready.promise();var K=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)K(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},L=function(a){return 1===a.nodeType||9===a.nodeType||!+a.nodeType};function M(){this.expando=n.expando+M.uid++}M.uid=1,M.prototype={register:function(a,b){var c=b||{};return a.nodeType?a[this.expando]=c:Object.defineProperty(a,this.expando,{value:c,writable:!0,configurable:!0}),a[this.expando]},cache:function(a){if(!L(a))return{};var b=a[this.expando];return b||(b={},L(a)&&(a.nodeType?a[this.expando]=b:Object.defineProperty(a,this.expando,{value:b,configurable:!0}))),b},set:function(a,b,c){var d,e=this.cache(a);if("string"==typeof b)e[b]=c;else for(d in b)e[d]=b[d];return e},get:function(a,b){return void 0===b?this.cache(a):a[this.expando]&&a[this.expando][b]},access:function(a,b,c){var d;return void 0===b||b&&"string"==typeof b&&void 0===c?(d=this.get(a,b),void 0!==d?d:this.get(a,n.camelCase(b))):(this.set(a,b,c),void 0!==c?c:b)},remove:function(a,b){var c,d,e,f=a[this.expando];if(void 0!==f){if(void 0===b)this.register(a);else{n.isArray(b)?d=b.concat(b.map(n.camelCase)):(e=n.camelCase(b),b in f?d=[b,e]:(d=e,d=d in f?[d]:d.match(G)||[])),c=d.length;while(c--)delete f[d[c]]}(void 0===b||n.isEmptyObject(f))&&(a.nodeType?a[this.expando]=void 0:delete a[this.expando])}},hasData:function(a){var b=a[this.expando];return void 0!==b&&!n.isEmptyObject(b)}};var N=new M,O=new M,P=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,Q=/[A-Z]/g;function R(a,b,c){var d;if(void 0===c&&1===a.nodeType)if(d="data-"+b.replace(Q,"-$&").toLowerCase(),c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:P.test(c)?n.parseJSON(c):c;
}catch(e){}O.set(a,b,c)}else c=void 0;return c}n.extend({hasData:function(a){return O.hasData(a)||N.hasData(a)},data:function(a,b,c){return O.access(a,b,c)},removeData:function(a,b){O.remove(a,b)},_data:function(a,b,c){return N.access(a,b,c)},_removeData:function(a,b){N.remove(a,b)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=O.get(f),1===f.nodeType&&!N.get(f,"hasDataAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),R(f,d,e[d])));N.set(f,"hasDataAttrs",!0)}return e}return"object"==typeof a?this.each(function(){O.set(this,a)}):K(this,function(b){var c,d;if(f&&void 0===b){if(c=O.get(f,a)||O.get(f,a.replace(Q,"-$&").toLowerCase()),void 0!==c)return c;if(d=n.camelCase(a),c=O.get(f,d),void 0!==c)return c;if(c=R(f,d,void 0),void 0!==c)return c}else d=n.camelCase(a),this.each(function(){var c=O.get(this,d);O.set(this,d,b),a.indexOf("-")>-1&&void 0!==c&&O.set(this,a,b)})},null,b,arguments.length>1,null,!0)},removeData:function(a){return this.each(function(){O.remove(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=N.get(a,b),c&&(!d||n.isArray(c)?d=N.access(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return N.get(a,c)||N.access(a,c,{empty:n.Callbacks("once memory").add(function(){N.remove(a,[b+"queue",c])})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?n.queue(this[0],a):void 0===b?this:this.each(function(){var c=n.queue(this,a,b);n._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&n.dequeue(this,a)})},dequeue:function(a){return this.each(function(){n.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=n.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=N.get(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var S=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=new RegExp("^(?:([+-])=|)("+S+")([a-z%]*)$","i"),U=["Top","Right","Bottom","Left"],V=function(a,b){return a=b||a,"none"===n.css(a,"display")||!n.contains(a.ownerDocument,a)};function W(a,b,c,d){var e,f=1,g=20,h=d?function(){return d.cur()}:function(){return n.css(a,b,"")},i=h(),j=c&&c[3]||(n.cssNumber[b]?"":"px"),k=(n.cssNumber[b]||"px"!==j&&+i)&&T.exec(n.css(a,b));if(k&&k[3]!==j){j=j||k[3],c=c||[],k=+i||1;do f=f||".5",k/=f,n.style(a,b,k+j);while(f!==(f=h()/i)&&1!==f&&--g)}return c&&(k=+k||+i||0,e=c[1]?k+(c[1]+1)*c[2]:+c[2],d&&(d.unit=j,d.start=k,d.end=e)),e}var X=/^(?:checkbox|radio)$/i,Y=/<([\w:-]+)/,Z=/^$|\/(?:java|ecma)script/i,$={option:[1,"<select multiple='multiple'>","</select>"],thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};$.optgroup=$.option,$.tbody=$.tfoot=$.colgroup=$.caption=$.thead,$.th=$.td;function _(a,b){var c="undefined"!=typeof a.getElementsByTagName?a.getElementsByTagName(b||"*"):"undefined"!=typeof a.querySelectorAll?a.querySelectorAll(b||"*"):[];return void 0===b||b&&n.nodeName(a,b)?n.merge([a],c):c}function aa(a,b){for(var c=0,d=a.length;d>c;c++)N.set(a[c],"globalEval",!b||N.get(b[c],"globalEval"))}var ba=/<|&#?\w+;/;function ca(a,b,c,d,e){for(var f,g,h,i,j,k,l=b.createDocumentFragment(),m=[],o=0,p=a.length;p>o;o++)if(f=a[o],f||0===f)if("object"===n.type(f))n.merge(m,f.nodeType?[f]:f);else if(ba.test(f)){g=g||l.appendChild(b.createElement("div")),h=(Y.exec(f)||["",""])[1].toLowerCase(),i=$[h]||$._default,g.innerHTML=i[1]+n.htmlPrefilter(f)+i[2],k=i[0];while(k--)g=g.lastChild;n.merge(m,g.childNodes),g=l.firstChild,g.textContent=""}else m.push(b.createTextNode(f));l.textContent="",o=0;while(f=m[o++])if(d&&n.inArray(f,d)>-1)e&&e.push(f);else if(j=n.contains(f.ownerDocument,f),g=_(l.appendChild(f),"script"),j&&aa(g),c){k=0;while(f=g[k++])Z.test(f.type||"")&&c.push(f)}return l}!function(){var a=d.createDocumentFragment(),b=a.appendChild(d.createElement("div")),c=d.createElement("input");c.setAttribute("type","radio"),c.setAttribute("checked","checked"),c.setAttribute("name","t"),b.appendChild(c),l.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,b.innerHTML="<textarea>x</textarea>",l.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var da=/^key/,ea=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,fa=/^([^.]*)(?:\.(.+)|)/;function ga(){return!0}function ha(){return!1}function ia(){try{return d.activeElement}catch(a){}}function ja(a,b,c,d,e,f){var g,h;if("object"==typeof b){"string"!=typeof c&&(d=d||c,c=void 0);for(h in b)ja(a,h,c,d,b[h],f);return a}if(null==d&&null==e?(e=c,d=c=void 0):null==e&&("string"==typeof c?(e=d,d=void 0):(e=d,d=c,c=void 0)),e===!1)e=ha;else if(!e)return a;return 1===f&&(g=e,e=function(a){return n().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=n.guid++)),a.each(function(){n.event.add(this,b,e,d,c)})}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=N.get(a);if(r){c.handler&&(f=c,c=f.handler,e=f.selector),c.guid||(c.guid=n.guid++),(i=r.events)||(i=r.events={}),(g=r.handle)||(g=r.handle=function(b){return"undefined"!=typeof n&&n.event.triggered!==b.type?n.event.dispatch.apply(a,arguments):void 0}),b=(b||"").match(G)||[""],j=b.length;while(j--)h=fa.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o&&(l=n.event.special[o]||{},o=(e?l.delegateType:l.bindType)||o,l=n.event.special[o]||{},k=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},f),(m=i[o])||(m=i[o]=[],m.delegateCount=0,l.setup&&l.setup.call(a,d,p,g)!==!1||a.addEventListener&&a.addEventListener(o,g)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),n.event.global[o]=!0)}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=N.hasData(a)&&N.get(a);if(r&&(i=r.events)){b=(b||"").match(G)||[""],j=b.length;while(j--)if(h=fa.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=i[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),g=f=m.length;while(f--)k=m[f],!e&&q!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&("**"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete i[o])}else for(o in i)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(i)&&N.remove(a,"handle events")}},dispatch:function(a){a=n.event.fix(a);var b,c,d,f,g,h=[],i=e.call(arguments),j=(N.get(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,c=0;while((g=f.handlers[c++])&&!a.isImmediatePropagationStopped())a.rnamespace&&!a.rnamespace.test(g.namespace)||(a.handleObj=g,a.data=g.data,d=((n.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i),void 0!==d&&(a.result=d)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&("click"!==a.type||isNaN(a.button)||a.button<1))for(;i!==this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(d=[],c=0;h>c;c++)f=b[c],e=f.selector+" ",void 0===d[e]&&(d[e]=f.needsContext?n(e,this).index(i)>-1:n.find(e,this,null,[i]).length),d[e]&&d.push(f);d.length&&g.push({elem:i,handlers:d})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},props:"altKey bubbles cancelable ctrlKey currentTarget detail eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,e,f,g=b.button;return null==a.pageX&&null!=b.clientX&&(c=a.target.ownerDocument||d,e=c.documentElement,f=c.body,a.pageX=b.clientX+(e&&e.scrollLeft||f&&f.scrollLeft||0)-(e&&e.clientLeft||f&&f.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||f&&f.scrollTop||0)-(e&&e.clientTop||f&&f.clientTop||0)),a.which||void 0===g||(a.which=1&g?1:2&g?3:4&g?2:0),a}},fix:function(a){if(a[n.expando])return a;var b,c,e,f=a.type,g=a,h=this.fixHooks[f];h||(this.fixHooks[f]=h=ea.test(f)?this.mouseHooks:da.test(f)?this.keyHooks:{}),e=h.props?this.props.concat(h.props):this.props,a=new n.Event(g),b=e.length;while(b--)c=e[b],a[c]=g[c];return a.target||(a.target=d),3===a.target.nodeType&&(a.target=a.target.parentNode),h.filter?h.filter(a,g):a},special:{load:{noBubble:!0},focus:{trigger:function(){return this!==ia()&&this.focus?(this.focus(),!1):void 0},delegateType:"focusin"},blur:{trigger:function(){return this===ia()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return"checkbox"===this.type&&this.click&&n.nodeName(this,"input")?(this.click(),!1):void 0},_default:function(a){return n.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}}},n.removeEvent=function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c)},n.Event=function(a,b){return this instanceof n.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?ga:ha):this.type=a,b&&n.extend(this,b),this.timeStamp=a&&a.timeStamp||n.now(),void(this[n.expando]=!0)):new n.Event(a,b)},n.Event.prototype={constructor:n.Event,isDefaultPrevented:ha,isPropagationStopped:ha,isImmediatePropagationStopped:ha,isSimulated:!1,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=ga,a&&!this.isSimulated&&a.preventDefault()},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=ga,a&&!this.isSimulated&&a.stopPropagation()},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=ga,a&&!this.isSimulated&&a.stopImmediatePropagation(),this.stopPropagation()}},n.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){n.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return e&&(e===d||n.contains(d,e))||(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),n.fn.extend({on:function(a,b,c,d){return ja(this,a,b,c,d)},one:function(a,b,c,d){return ja(this,a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,n(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return b!==!1&&"function"!=typeof b||(c=b,b=void 0),c===!1&&(c=ha),this.each(function(){n.event.remove(this,a,c,b)})}});var ka=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi,la=/<script|<style|<link/i,ma=/checked\s*(?:[^=]|=\s*.checked.)/i,na=/^true\/(.*)/,oa=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;function pa(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function qa(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function ra(a){var b=na.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function sa(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(N.hasData(a)&&(f=N.access(a),g=N.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;d>c;c++)n.event.add(b,e,j[e][c])}O.hasData(a)&&(h=O.access(a),i=n.extend({},h),O.set(b,i))}}function ta(a,b){var c=b.nodeName.toLowerCase();"input"===c&&X.test(a.type)?b.checked=a.checked:"input"!==c&&"textarea"!==c||(b.defaultValue=a.defaultValue)}function ua(a,b,c,d){b=f.apply([],b);var e,g,h,i,j,k,m=0,o=a.length,p=o-1,q=b[0],r=n.isFunction(q);if(r||o>1&&"string"==typeof q&&!l.checkClone&&ma.test(q))return a.each(function(e){var f=a.eq(e);r&&(b[0]=q.call(this,e,f.html())),ua(f,b,c,d)});if(o&&(e=ca(b,a[0].ownerDocument,!1,a,d),g=e.firstChild,1===e.childNodes.length&&(e=g),g||d)){for(h=n.map(_(e,"script"),qa),i=h.length;o>m;m++)j=e,m!==p&&(j=n.clone(j,!0,!0),i&&n.merge(h,_(j,"script"))),c.call(a[m],j,m);if(i)for(k=h[h.length-1].ownerDocument,n.map(h,ra),m=0;i>m;m++)j=h[m],Z.test(j.type||"")&&!N.access(j,"globalEval")&&n.contains(k,j)&&(j.src?n._evalUrl&&n._evalUrl(j.src):n.globalEval(j.textContent.replace(oa,"")))}return a}function va(a,b,c){for(var d,e=b?n.filter(b,a):a,f=0;null!=(d=e[f]);f++)c||1!==d.nodeType||n.cleanData(_(d)),d.parentNode&&(c&&n.contains(d.ownerDocument,d)&&aa(_(d,"script")),d.parentNode.removeChild(d));return a}n.extend({htmlPrefilter:function(a){return a.replace(ka,"<$1></$2>")},clone:function(a,b,c){var d,e,f,g,h=a.cloneNode(!0),i=n.contains(a.ownerDocument,a);if(!(l.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(g=_(h),f=_(a),d=0,e=f.length;e>d;d++)ta(f[d],g[d]);if(b)if(c)for(f=f||_(a),g=g||_(h),d=0,e=f.length;e>d;d++)sa(f[d],g[d]);else sa(a,h);return g=_(h,"script"),g.length>0&&aa(g,!i&&_(a,"script")),h},cleanData:function(a){for(var b,c,d,e=n.event.special,f=0;void 0!==(c=a[f]);f++)if(L(c)){if(b=c[N.expando]){if(b.events)for(d in b.events)e[d]?n.event.remove(c,d):n.removeEvent(c,d,b.handle);c[N.expando]=void 0}c[O.expando]&&(c[O.expando]=void 0)}}}),n.fn.extend({domManip:ua,detach:function(a){return va(this,a,!0)},remove:function(a){return va(this,a)},text:function(a){return K(this,function(a){return void 0===a?n.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=a)})},null,a,arguments.length)},append:function(){return ua(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=pa(this,a);b.appendChild(a)}})},prepend:function(){return ua(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=pa(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return ua(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return ua(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)1===a.nodeType&&(n.cleanData(_(a,!1)),a.textContent="");return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return K(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a&&1===b.nodeType)return b.innerHTML;if("string"==typeof a&&!la.test(a)&&!$[(Y.exec(a)||["",""])[1].toLowerCase()]){a=n.htmlPrefilter(a);try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(_(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=[];return ua(this,arguments,function(b){var c=this.parentNode;n.inArray(this,a)<0&&(n.cleanData(_(this)),c&&c.replaceChild(b,this))},a)}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=[],e=n(a),f=e.length-1,h=0;f>=h;h++)c=h===f?this:this.clone(!0),n(e[h])[b](c),g.apply(d,c.get());return this.pushStack(d)}});var wa,xa={HTML:"block",BODY:"block"};function ya(a,b){var c=n(b.createElement(a)).appendTo(b.body),d=n.css(c[0],"display");return c.detach(),d}function za(a){var b=d,c=xa[a];return c||(c=ya(a,b),"none"!==c&&c||(wa=(wa||n("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=wa[0].contentDocument,b.write(),b.close(),c=ya(a,b),wa.detach()),xa[a]=c),c}var Aa=/^margin/,Ba=new RegExp("^("+S+")(?!px)[a-z%]+$","i"),Ca=function(b){var c=b.ownerDocument.defaultView;return c&&c.opener||(c=a),c.getComputedStyle(b)},Da=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e},Ea=d.documentElement;!function(){var b,c,e,f,g=d.createElement("div"),h=d.createElement("div");if(h.style){h.style.backgroundClip="content-box",h.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===h.style.backgroundClip,g.style.cssText="border:0;width:8px;height:0;top:0;left:-9999px;padding:0;margin-top:1px;position:absolute",g.appendChild(h);function i(){h.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;position:relative;display:block;margin:auto;border:1px;padding:1px;top:1%;width:50%",h.innerHTML="",Ea.appendChild(g);var d=a.getComputedStyle(h);b="1%"!==d.top,f="2px"===d.marginLeft,c="4px"===d.width,h.style.marginRight="50%",e="4px"===d.marginRight,Ea.removeChild(g)}n.extend(l,{pixelPosition:function(){return i(),b},boxSizingReliable:function(){return null==c&&i(),c},pixelMarginRight:function(){return null==c&&i(),e},reliableMarginLeft:function(){return null==c&&i(),f},reliableMarginRight:function(){var b,c=h.appendChild(d.createElement("div"));return c.style.cssText=h.style.cssText="-webkit-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",c.style.marginRight=c.style.width="0",h.style.width="1px",Ea.appendChild(g),b=!parseFloat(a.getComputedStyle(c).marginRight),Ea.removeChild(g),h.removeChild(c),b}})}}();function Fa(a,b,c){var d,e,f,g,h=a.style;return c=c||Ca(a),g=c?c.getPropertyValue(b)||c[b]:void 0,""!==g&&void 0!==g||n.contains(a.ownerDocument,a)||(g=n.style(a,b)),c&&!l.pixelMarginRight()&&Ba.test(g)&&Aa.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f),void 0!==g?g+"":g}function Ga(a,b){return{get:function(){return a()?void delete this.get:(this.get=b).apply(this,arguments)}}}var Ha=/^(none|table(?!-c[ea]).+)/,Ia={position:"absolute",visibility:"hidden",display:"block"},Ja={letterSpacing:"0",fontWeight:"400"},Ka=["Webkit","O","Moz","ms"],La=d.createElement("div").style;function Ma(a){if(a in La)return a;var b=a[0].toUpperCase()+a.slice(1),c=Ka.length;while(c--)if(a=Ka[c]+b,a in La)return a}function Na(a,b,c){var d=T.exec(b);return d?Math.max(0,d[2]-(c||0))+(d[3]||"px"):b}function Oa(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=n.css(a,c+U[f],!0,e)),d?("content"===c&&(g-=n.css(a,"padding"+U[f],!0,e)),"margin"!==c&&(g-=n.css(a,"border"+U[f]+"Width",!0,e))):(g+=n.css(a,"padding"+U[f],!0,e),"padding"!==c&&(g+=n.css(a,"border"+U[f]+"Width",!0,e)));return g}function Pa(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ca(a),g="border-box"===n.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Fa(a,b,f),(0>e||null==e)&&(e=a.style[b]),Ba.test(e))return e;d=g&&(l.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Oa(a,b,c||(g?"border":"content"),d,f)+"px"}function Qa(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=N.get(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&V(d)&&(f[g]=N.access(d,"olddisplay",za(d.nodeName)))):(e=V(d),"none"===c&&e||N.set(d,"olddisplay",e?c:n.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}n.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Fa(a,"opacity");return""===c?"1":c}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":"cssFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=n.camelCase(b),i=a.style;return b=n.cssProps[h]||(n.cssProps[h]=Ma(h)||h),g=n.cssHooks[b]||n.cssHooks[h],void 0===c?g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b]:(f=typeof c,"string"===f&&(e=T.exec(c))&&e[1]&&(c=W(a,b,e),f="number"),null!=c&&c===c&&("number"===f&&(c+=e&&e[3]||(n.cssNumber[h]?"":"px")),l.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),g&&"set"in g&&void 0===(c=g.set(a,c,d))||(i[b]=c)),void 0)}},css:function(a,b,c,d){var e,f,g,h=n.camelCase(b);return b=n.cssProps[h]||(n.cssProps[h]=Ma(h)||h),g=n.cssHooks[b]||n.cssHooks[h],g&&"get"in g&&(e=g.get(a,!0,c)),void 0===e&&(e=Fa(a,b,d)),"normal"===e&&b in Ja&&(e=Ja[b]),""===c||c?(f=parseFloat(e),c===!0||isFinite(f)?f||0:e):e}}),n.each(["height","width"],function(a,b){n.cssHooks[b]={get:function(a,c,d){return c?Ha.test(n.css(a,"display"))&&0===a.offsetWidth?Da(a,Ia,function(){return Pa(a,b,d)}):Pa(a,b,d):void 0},set:function(a,c,d){var e,f=d&&Ca(a),g=d&&Oa(a,b,d,"border-box"===n.css(a,"boxSizing",!1,f),f);return g&&(e=T.exec(c))&&"px"!==(e[3]||"px")&&(a.style[b]=c,c=n.css(a,b)),Na(a,c,g)}}}),n.cssHooks.marginLeft=Ga(l.reliableMarginLeft,function(a,b){return b?(parseFloat(Fa(a,"marginLeft"))||a.getBoundingClientRect().left-Da(a,{marginLeft:0},function(){return a.getBoundingClientRect().left}))+"px":void 0}),n.cssHooks.marginRight=Ga(l.reliableMarginRight,function(a,b){return b?Da(a,{display:"inline-block"},Fa,[a,"marginRight"]):void 0}),n.each({margin:"",padding:"",border:"Width"},function(a,b){n.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+U[d]+b]=f[d]||f[d-2]||f[0];return e}},Aa.test(a)||(n.cssHooks[a+b].set=Na)}),n.fn.extend({css:function(a,b){return K(this,function(a,b,c){var d,e,f={},g=0;if(n.isArray(b)){for(d=Ca(a),e=b.length;e>g;g++)f[b[g]]=n.css(a,b[g],!1,d);return f}return void 0!==c?n.style(a,b,c):n.css(a,b)},a,b,arguments.length>1)},show:function(){return Qa(this,!0)},hide:function(){return Qa(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){V(this)?n(this).show():n(this).hide()})}});function Ra(a,b,c,d,e){return new Ra.prototype.init(a,b,c,d,e)}n.Tween=Ra,Ra.prototype={constructor:Ra,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||n.easing._default,this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(n.cssNumber[c]?"":"px")},cur:function(){var a=Ra.propHooks[this.prop];return a&&a.get?a.get(this):Ra.propHooks._default.get(this)},run:function(a){var b,c=Ra.propHooks[this.prop];return this.options.duration?this.pos=b=n.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Ra.propHooks._default.set(this),this}},Ra.prototype.init.prototype=Ra.prototype,Ra.propHooks={_default:{get:function(a){var b;return 1!==a.elem.nodeType||null!=a.elem[a.prop]&&null==a.elem.style[a.prop]?a.elem[a.prop]:(b=n.css(a.elem,a.prop,""),b&&"auto"!==b?b:0)},set:function(a){n.fx.step[a.prop]?n.fx.step[a.prop](a):1!==a.elem.nodeType||null==a.elem.style[n.cssProps[a.prop]]&&!n.cssHooks[a.prop]?a.elem[a.prop]=a.now:n.style(a.elem,a.prop,a.now+a.unit)}}},Ra.propHooks.scrollTop=Ra.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},n.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2},_default:"swing"},n.fx=Ra.prototype.init,n.fx.step={};var Sa,Ta,Ua=/^(?:toggle|show|hide)$/,Va=/queueHooks$/;function Wa(){return a.setTimeout(function(){Sa=void 0}),Sa=n.now()}function Xa(a,b){var c,d=0,e={height:a};for(b=b?1:0;4>d;d+=2-b)c=U[d],e["margin"+c]=e["padding"+c]=a;return b&&(e.opacity=e.width=a),e}function Ya(a,b,c){for(var d,e=(_a.tweeners[b]||[]).concat(_a.tweeners["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function Za(a,b,c){var d,e,f,g,h,i,j,k,l=this,m={},o=a.style,p=a.nodeType&&V(a),q=N.get(a,"fxshow");c.queue||(h=n._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,l.always(function(){l.always(function(){h.unqueued--,n.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[o.overflow,o.overflowX,o.overflowY],j=n.css(a,"display"),k="none"===j?N.get(a,"olddisplay")||za(a.nodeName):j,"inline"===k&&"none"===n.css(a,"float")&&(o.display="inline-block")),c.overflow&&(o.overflow="hidden",l.always(function(){o.overflow=c.overflow[0],o.overflowX=c.overflow[1],o.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],Ua.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(p?"hide":"show")){if("show"!==e||!q||void 0===q[d])continue;p=!0}m[d]=q&&q[d]||n.style(a,d)}else j=void 0;if(n.isEmptyObject(m))"inline"===("none"===j?za(a.nodeName):j)&&(o.display=j);else{q?"hidden"in q&&(p=q.hidden):q=N.access(a,"fxshow",{}),f&&(q.hidden=!p),p?n(a).show():l.done(function(){n(a).hide()}),l.done(function(){var b;N.remove(a,"fxshow");for(b in m)n.style(a,b,m[b])});for(d in m)g=Ya(p?q[d]:0,d,l),d in q||(q[d]=g.start,p&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function $a(a,b){var c,d,e,f,g;for(c in a)if(d=n.camelCase(c),e=b[d],f=a[c],n.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=n.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function _a(a,b,c){var d,e,f=0,g=_a.prefilters.length,h=n.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=Sa||Wa(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:n.extend({},b),opts:n.extend(!0,{specialEasing:{},easing:n.easing._default},c),originalProperties:b,originalOptions:c,startTime:Sa||Wa(),duration:c.duration,tweens:[],createTween:function(b,c){var d=n.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?(h.notifyWith(a,[j,1,0]),h.resolveWith(a,[j,b])):h.rejectWith(a,[j,b]),this}}),k=j.props;for($a(k,j.opts.specialEasing);g>f;f++)if(d=_a.prefilters[f].call(j,a,k,j.opts))return n.isFunction(d.stop)&&(n._queueHooks(j.elem,j.opts.queue).stop=n.proxy(d.stop,d)),d;return n.map(k,Ya,j),n.isFunction(j.opts.start)&&j.opts.start.call(a,j),n.fx.timer(n.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}n.Animation=n.extend(_a,{tweeners:{"*":[function(a,b){var c=this.createTween(a,b);return W(c.elem,a,T.exec(b),c),c}]},tweener:function(a,b){n.isFunction(a)?(b=a,a=["*"]):a=a.match(G);for(var c,d=0,e=a.length;e>d;d++)c=a[d],_a.tweeners[c]=_a.tweeners[c]||[],_a.tweeners[c].unshift(b)},prefilters:[Za],prefilter:function(a,b){b?_a.prefilters.unshift(a):_a.prefilters.push(a)}}),n.speed=function(a,b,c){var d=a&&"object"==typeof a?n.extend({},a):{complete:c||!c&&b||n.isFunction(a)&&a,duration:a,easing:c&&b||b&&!n.isFunction(b)&&b};return d.duration=n.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in n.fx.speeds?n.fx.speeds[d.duration]:n.fx.speeds._default,null!=d.queue&&d.queue!==!0||(d.queue="fx"),d.old=d.complete,d.complete=function(){n.isFunction(d.old)&&d.old.call(this),d.queue&&n.dequeue(this,d.queue)},d},n.fn.extend({fadeTo:function(a,b,c,d){return this.filter(V).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=n.isEmptyObject(a),f=n.speed(b,c,d),g=function(){var b=_a(this,n.extend({},a),f);(e||N.get(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=n.timers,g=N.get(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&Va.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));!b&&c||n.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=N.get(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=n.timers,g=d?d.length:0;for(c.finish=!0,n.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),n.each(["toggle","show","hide"],function(a,b){var c=n.fn[b];n.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(Xa(b,!0),a,d,e)}}),n.each({slideDown:Xa("show"),slideUp:Xa("hide"),slideToggle:Xa("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){n.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),n.timers=[],n.fx.tick=function(){var a,b=0,c=n.timers;for(Sa=n.now();b<c.length;b++)a=c[b],a()||c[b]!==a||c.splice(b--,1);c.length||n.fx.stop(),Sa=void 0},n.fx.timer=function(a){n.timers.push(a),a()?n.fx.start():n.timers.pop()},n.fx.interval=13,n.fx.start=function(){Ta||(Ta=a.setInterval(n.fx.tick,n.fx.interval))},n.fx.stop=function(){a.clearInterval(Ta),Ta=null},n.fx.speeds={slow:600,fast:200,_default:400},n.fn.delay=function(b,c){return b=n.fx?n.fx.speeds[b]||b:b,c=c||"fx",this.queue(c,function(c,d){var e=a.setTimeout(c,b);d.stop=function(){a.clearTimeout(e)}})},function(){var a=d.createElement("input"),b=d.createElement("select"),c=b.appendChild(d.createElement("option"));a.type="checkbox",l.checkOn=""!==a.value,l.optSelected=c.selected,b.disabled=!0,l.optDisabled=!c.disabled,a=d.createElement("input"),a.value="t",a.type="radio",l.radioValue="t"===a.value}();var ab,bb=n.expr.attrHandle;n.fn.extend({attr:function(a,b){return K(this,n.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){n.removeAttr(this,a)})}}),n.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return"undefined"==typeof a.getAttribute?n.prop(a,b,c):(1===f&&n.isXMLDoc(a)||(b=b.toLowerCase(),e=n.attrHooks[b]||(n.expr.match.bool.test(b)?ab:void 0)),void 0!==c?null===c?void n.removeAttr(a,b):e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:(a.setAttribute(b,c+""),c):e&&"get"in e&&null!==(d=e.get(a,b))?d:(d=n.find.attr(a,b),null==d?void 0:d))},attrHooks:{type:{set:function(a,b){if(!l.radioValue&&"radio"===b&&n.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(G);if(f&&1===a.nodeType)while(c=f[e++])d=n.propFix[c]||c,n.expr.match.bool.test(c)&&(a[d]=!1),a.removeAttribute(c)}}),ab={set:function(a,b,c){return b===!1?n.removeAttr(a,c):a.setAttribute(c,c),c}},n.each(n.expr.match.bool.source.match(/\w+/g),function(a,b){var c=bb[b]||n.find.attr;bb[b]=function(a,b,d){var e,f;return d||(f=bb[b],bb[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,bb[b]=f),e}});var cb=/^(?:input|select|textarea|button)$/i,db=/^(?:a|area)$/i;n.fn.extend({prop:function(a,b){return K(this,n.prop,a,b,arguments.length>1)},removeProp:function(a){return this.each(function(){delete this[n.propFix[a]||a]})}}),n.extend({prop:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return 1===f&&n.isXMLDoc(a)||(b=n.propFix[b]||b,e=n.propHooks[b]),
void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=n.find.attr(a,"tabindex");return b?parseInt(b,10):cb.test(a.nodeName)||db.test(a.nodeName)&&a.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),l.optSelected||(n.propHooks.selected={get:function(a){var b=a.parentNode;return b&&b.parentNode&&b.parentNode.selectedIndex,null},set:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex)}}),n.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){n.propFix[this.toLowerCase()]=this});var eb=/[\t\r\n\f]/g;function fb(a){return a.getAttribute&&a.getAttribute("class")||""}n.fn.extend({addClass:function(a){var b,c,d,e,f,g,h,i=0;if(n.isFunction(a))return this.each(function(b){n(this).addClass(a.call(this,b,fb(this)))});if("string"==typeof a&&a){b=a.match(G)||[];while(c=this[i++])if(e=fb(c),d=1===c.nodeType&&(" "+e+" ").replace(eb," ")){g=0;while(f=b[g++])d.indexOf(" "+f+" ")<0&&(d+=f+" ");h=n.trim(d),e!==h&&c.setAttribute("class",h)}}return this},removeClass:function(a){var b,c,d,e,f,g,h,i=0;if(n.isFunction(a))return this.each(function(b){n(this).removeClass(a.call(this,b,fb(this)))});if(!arguments.length)return this.attr("class","");if("string"==typeof a&&a){b=a.match(G)||[];while(c=this[i++])if(e=fb(c),d=1===c.nodeType&&(" "+e+" ").replace(eb," ")){g=0;while(f=b[g++])while(d.indexOf(" "+f+" ")>-1)d=d.replace(" "+f+" "," ");h=n.trim(d),e!==h&&c.setAttribute("class",h)}}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):n.isFunction(a)?this.each(function(c){n(this).toggleClass(a.call(this,c,fb(this),b),b)}):this.each(function(){var b,d,e,f;if("string"===c){d=0,e=n(this),f=a.match(G)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else void 0!==a&&"boolean"!==c||(b=fb(this),b&&N.set(this,"__className__",b),this.setAttribute&&this.setAttribute("class",b||a===!1?"":N.get(this,"__className__")||""))})},hasClass:function(a){var b,c,d=0;b=" "+a+" ";while(c=this[d++])if(1===c.nodeType&&(" "+fb(c)+" ").replace(eb," ").indexOf(b)>-1)return!0;return!1}});var gb=/\r/g,hb=/[\x20\t\r\n\f]+/g;n.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e?e+="":n.isArray(e)&&(e=n.map(e,function(a){return null==a?"":a+""})),b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(gb,""):null==c?"":c)}}}),n.extend({valHooks:{option:{get:function(a){var b=n.find.attr(a,"value");return null!=b?b:n.trim(n.text(a)).replace(hb," ")}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],(c.selected||i===e)&&(l.optDisabled?!c.disabled:null===c.getAttribute("disabled"))&&(!c.parentNode.disabled||!n.nodeName(c.parentNode,"optgroup"))){if(b=n(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=n.makeArray(b),g=e.length;while(g--)d=e[g],(d.selected=n.inArray(n.valHooks.option.get(d),f)>-1)&&(c=!0);return c||(a.selectedIndex=-1),f}}}}),n.each(["radio","checkbox"],function(){n.valHooks[this]={set:function(a,b){return n.isArray(b)?a.checked=n.inArray(n(a).val(),b)>-1:void 0}},l.checkOn||(n.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var ib=/^(?:focusinfocus|focusoutblur)$/;n.extend(n.event,{trigger:function(b,c,e,f){var g,h,i,j,l,m,o,p=[e||d],q=k.call(b,"type")?b.type:b,r=k.call(b,"namespace")?b.namespace.split("."):[];if(h=i=e=e||d,3!==e.nodeType&&8!==e.nodeType&&!ib.test(q+n.event.triggered)&&(q.indexOf(".")>-1&&(r=q.split("."),q=r.shift(),r.sort()),l=q.indexOf(":")<0&&"on"+q,b=b[n.expando]?b:new n.Event(q,"object"==typeof b&&b),b.isTrigger=f?2:3,b.namespace=r.join("."),b.rnamespace=b.namespace?new RegExp("(^|\\.)"+r.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=e),c=null==c?[b]:n.makeArray(c,[b]),o=n.event.special[q]||{},f||!o.trigger||o.trigger.apply(e,c)!==!1)){if(!f&&!o.noBubble&&!n.isWindow(e)){for(j=o.delegateType||q,ib.test(j+q)||(h=h.parentNode);h;h=h.parentNode)p.push(h),i=h;i===(e.ownerDocument||d)&&p.push(i.defaultView||i.parentWindow||a)}g=0;while((h=p[g++])&&!b.isPropagationStopped())b.type=g>1?j:o.bindType||q,m=(N.get(h,"events")||{})[b.type]&&N.get(h,"handle"),m&&m.apply(h,c),m=l&&h[l],m&&m.apply&&L(h)&&(b.result=m.apply(h,c),b.result===!1&&b.preventDefault());return b.type=q,f||b.isDefaultPrevented()||o._default&&o._default.apply(p.pop(),c)!==!1||!L(e)||l&&n.isFunction(e[q])&&!n.isWindow(e)&&(i=e[l],i&&(e[l]=null),n.event.triggered=q,e[q](),n.event.triggered=void 0,i&&(e[l]=i)),b.result}},simulate:function(a,b,c){var d=n.extend(new n.Event,c,{type:a,isSimulated:!0});n.event.trigger(d,null,b)}}),n.fn.extend({trigger:function(a,b){return this.each(function(){n.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?n.event.trigger(a,b,c,!0):void 0}}),n.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){n.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),n.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),l.focusin="onfocusin"in a,l.focusin||n.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){n.event.simulate(b,a.target,n.event.fix(a))};n.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=N.access(d,b);e||d.addEventListener(a,c,!0),N.access(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=N.access(d,b)-1;e?N.access(d,b,e):(d.removeEventListener(a,c,!0),N.remove(d,b))}}});var jb=a.location,kb=n.now(),lb=/\?/;n.parseJSON=function(a){return JSON.parse(a+"")},n.parseXML=function(b){var c;if(!b||"string"!=typeof b)return null;try{c=(new a.DOMParser).parseFromString(b,"text/xml")}catch(d){c=void 0}return c&&!c.getElementsByTagName("parsererror").length||n.error("Invalid XML: "+b),c};var mb=/#.*$/,nb=/([?&])_=[^&]*/,ob=/^(.*?):[ \t]*([^\r\n]*)$/gm,pb=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,qb=/^(?:GET|HEAD)$/,rb=/^\/\//,sb={},tb={},ub="*/".concat("*"),vb=d.createElement("a");vb.href=jb.href;function wb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(G)||[];if(n.isFunction(c))while(d=f[e++])"+"===d[0]?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function xb(a,b,c,d){var e={},f=a===tb;function g(h){var i;return e[h]=!0,n.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function yb(a,b){var c,d,e=n.ajaxSettings.flatOptions||{};for(c in b)void 0!==b[c]&&((e[c]?a:d||(d={}))[c]=b[c]);return d&&n.extend(!0,a,d),a}function zb(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===d&&(d=a.mimeType||b.getResponseHeader("Content-Type"));if(d)for(e in h)if(h[e]&&h[e].test(d)){i.unshift(e);break}if(i[0]in c)f=i[0];else{for(e in c){if(!i[0]||a.converters[e+" "+i[0]]){f=e;break}g||(g=e)}f=f||g}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Ab(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}n.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:jb.href,type:"GET",isLocal:pb.test(jb.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":ub,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":n.parseJSON,"text xml":n.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?yb(yb(a,n.ajaxSettings),b):yb(n.ajaxSettings,a)},ajaxPrefilter:wb(sb),ajaxTransport:wb(tb),ajax:function(b,c){"object"==typeof b&&(c=b,b=void 0),c=c||{};var e,f,g,h,i,j,k,l,m=n.ajaxSetup({},c),o=m.context||m,p=m.context&&(o.nodeType||o.jquery)?n(o):n.event,q=n.Deferred(),r=n.Callbacks("once memory"),s=m.statusCode||{},t={},u={},v=0,w="canceled",x={readyState:0,getResponseHeader:function(a){var b;if(2===v){if(!h){h={};while(b=ob.exec(g))h[b[1].toLowerCase()]=b[2]}b=h[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===v?g:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return v||(a=u[c]=u[c]||a,t[a]=b),this},overrideMimeType:function(a){return v||(m.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>v)for(b in a)s[b]=[s[b],a[b]];else x.always(a[x.status]);return this},abort:function(a){var b=a||w;return e&&e.abort(b),z(0,b),this}};if(q.promise(x).complete=r.add,x.success=x.done,x.error=x.fail,m.url=((b||m.url||jb.href)+"").replace(mb,"").replace(rb,jb.protocol+"//"),m.type=c.method||c.type||m.method||m.type,m.dataTypes=n.trim(m.dataType||"*").toLowerCase().match(G)||[""],null==m.crossDomain){j=d.createElement("a");try{j.href=m.url,j.href=j.href,m.crossDomain=vb.protocol+"//"+vb.host!=j.protocol+"//"+j.host}catch(y){m.crossDomain=!0}}if(m.data&&m.processData&&"string"!=typeof m.data&&(m.data=n.param(m.data,m.traditional)),xb(sb,m,c,x),2===v)return x;k=n.event&&m.global,k&&0===n.active++&&n.event.trigger("ajaxStart"),m.type=m.type.toUpperCase(),m.hasContent=!qb.test(m.type),f=m.url,m.hasContent||(m.data&&(f=m.url+=(lb.test(f)?"&":"?")+m.data,delete m.data),m.cache===!1&&(m.url=nb.test(f)?f.replace(nb,"$1_="+kb++):f+(lb.test(f)?"&":"?")+"_="+kb++)),m.ifModified&&(n.lastModified[f]&&x.setRequestHeader("If-Modified-Since",n.lastModified[f]),n.etag[f]&&x.setRequestHeader("If-None-Match",n.etag[f])),(m.data&&m.hasContent&&m.contentType!==!1||c.contentType)&&x.setRequestHeader("Content-Type",m.contentType),x.setRequestHeader("Accept",m.dataTypes[0]&&m.accepts[m.dataTypes[0]]?m.accepts[m.dataTypes[0]]+("*"!==m.dataTypes[0]?", "+ub+"; q=0.01":""):m.accepts["*"]);for(l in m.headers)x.setRequestHeader(l,m.headers[l]);if(m.beforeSend&&(m.beforeSend.call(o,x,m)===!1||2===v))return x.abort();w="abort";for(l in{success:1,error:1,complete:1})x[l](m[l]);if(e=xb(tb,m,c,x)){if(x.readyState=1,k&&p.trigger("ajaxSend",[x,m]),2===v)return x;m.async&&m.timeout>0&&(i=a.setTimeout(function(){x.abort("timeout")},m.timeout));try{v=1,e.send(t,z)}catch(y){if(!(2>v))throw y;z(-1,y)}}else z(-1,"No Transport");function z(b,c,d,h){var j,l,t,u,w,y=c;2!==v&&(v=2,i&&a.clearTimeout(i),e=void 0,g=h||"",x.readyState=b>0?4:0,j=b>=200&&300>b||304===b,d&&(u=zb(m,x,d)),u=Ab(m,u,x,j),j?(m.ifModified&&(w=x.getResponseHeader("Last-Modified"),w&&(n.lastModified[f]=w),w=x.getResponseHeader("etag"),w&&(n.etag[f]=w)),204===b||"HEAD"===m.type?y="nocontent":304===b?y="notmodified":(y=u.state,l=u.data,t=u.error,j=!t)):(t=y,!b&&y||(y="error",0>b&&(b=0))),x.status=b,x.statusText=(c||y)+"",j?q.resolveWith(o,[l,y,x]):q.rejectWith(o,[x,y,t]),x.statusCode(s),s=void 0,k&&p.trigger(j?"ajaxSuccess":"ajaxError",[x,m,j?l:t]),r.fireWith(o,[x,y]),k&&(p.trigger("ajaxComplete",[x,m]),--n.active||n.event.trigger("ajaxStop")))}return x},getJSON:function(a,b,c){return n.get(a,b,c,"json")},getScript:function(a,b){return n.get(a,void 0,b,"script")}}),n.each(["get","post"],function(a,b){n[b]=function(a,c,d,e){return n.isFunction(c)&&(e=e||d,d=c,c=void 0),n.ajax(n.extend({url:a,type:b,dataType:e,data:c,success:d},n.isPlainObject(a)&&a))}}),n._evalUrl=function(a){return n.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},n.fn.extend({wrapAll:function(a){var b;return n.isFunction(a)?this.each(function(b){n(this).wrapAll(a.call(this,b))}):(this[0]&&(b=n(a,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstElementChild)a=a.firstElementChild;return a}).append(this)),this)},wrapInner:function(a){return n.isFunction(a)?this.each(function(b){n(this).wrapInner(a.call(this,b))}):this.each(function(){var b=n(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=n.isFunction(a);return this.each(function(c){n(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){n.nodeName(this,"body")||n(this).replaceWith(this.childNodes)}).end()}}),n.expr.filters.hidden=function(a){return!n.expr.filters.visible(a)},n.expr.filters.visible=function(a){return a.offsetWidth>0||a.offsetHeight>0||a.getClientRects().length>0};var Bb=/%20/g,Cb=/\[\]$/,Db=/\r?\n/g,Eb=/^(?:submit|button|image|reset|file)$/i,Fb=/^(?:input|select|textarea|keygen)/i;function Gb(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||Cb.test(a)?d(a,e):Gb(a+"["+("object"==typeof e&&null!=e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)Gb(a+"["+e+"]",b[e],c,d)}n.param=function(a,b){var c,d=[],e=function(a,b){b=n.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=n.ajaxSettings&&n.ajaxSettings.traditional),n.isArray(a)||a.jquery&&!n.isPlainObject(a))n.each(a,function(){e(this.name,this.value)});else for(c in a)Gb(c,a[c],b,e);return d.join("&").replace(Bb,"+")},n.fn.extend({serialize:function(){return n.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=n.prop(this,"elements");return a?n.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!n(this).is(":disabled")&&Fb.test(this.nodeName)&&!Eb.test(a)&&(this.checked||!X.test(a))}).map(function(a,b){var c=n(this).val();return null==c?null:n.isArray(c)?n.map(c,function(a){return{name:b.name,value:a.replace(Db,"\r\n")}}):{name:b.name,value:c.replace(Db,"\r\n")}}).get()}}),n.ajaxSettings.xhr=function(){try{return new a.XMLHttpRequest}catch(b){}};var Hb={0:200,1223:204},Ib=n.ajaxSettings.xhr();l.cors=!!Ib&&"withCredentials"in Ib,l.ajax=Ib=!!Ib,n.ajaxTransport(function(b){var c,d;return l.cors||Ib&&!b.crossDomain?{send:function(e,f){var g,h=b.xhr();if(h.open(b.type,b.url,b.async,b.username,b.password),b.xhrFields)for(g in b.xhrFields)h[g]=b.xhrFields[g];b.mimeType&&h.overrideMimeType&&h.overrideMimeType(b.mimeType),b.crossDomain||e["X-Requested-With"]||(e["X-Requested-With"]="XMLHttpRequest");for(g in e)h.setRequestHeader(g,e[g]);c=function(a){return function(){c&&(c=d=h.onload=h.onerror=h.onabort=h.onreadystatechange=null,"abort"===a?h.abort():"error"===a?"number"!=typeof h.status?f(0,"error"):f(h.status,h.statusText):f(Hb[h.status]||h.status,h.statusText,"text"!==(h.responseType||"text")||"string"!=typeof h.responseText?{binary:h.response}:{text:h.responseText},h.getAllResponseHeaders()))}},h.onload=c(),d=h.onerror=c("error"),void 0!==h.onabort?h.onabort=d:h.onreadystatechange=function(){4===h.readyState&&a.setTimeout(function(){c&&d()})},c=c("abort");try{h.send(b.hasContent&&b.data||null)}catch(i){if(c)throw i}},abort:function(){c&&c()}}:void 0}),n.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(a){return n.globalEval(a),a}}}),n.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET")}),n.ajaxTransport("script",function(a){if(a.crossDomain){var b,c;return{send:function(e,f){b=n("<script>").prop({charset:a.scriptCharset,src:a.url}).on("load error",c=function(a){b.remove(),c=null,a&&f("error"===a.type?404:200,a.type)}),d.head.appendChild(b[0])},abort:function(){c&&c()}}}});var Jb=[],Kb=/(=)\?(?=&|$)|\?\?/;n.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=Jb.pop()||n.expando+"_"+kb++;return this[a]=!0,a}}),n.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(Kb.test(b.url)?"url":"string"==typeof b.data&&0===(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&Kb.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=n.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(Kb,"$1"+e):b.jsonp!==!1&&(b.url+=(lb.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||n.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){void 0===f?n(a).removeProp(e):a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,Jb.push(e)),g&&n.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),n.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||d;var e=x.exec(a),f=!c&&[];return e?[b.createElement(e[1])]:(e=ca([a],b,f),f&&f.length&&n(f).remove(),n.merge([],e.childNodes))};var Lb=n.fn.load;n.fn.load=function(a,b,c){if("string"!=typeof a&&Lb)return Lb.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>-1&&(d=n.trim(a.slice(h)),a=a.slice(0,h)),n.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(e="POST"),g.length>0&&n.ajax({url:a,type:e||"GET",dataType:"html",data:b}).done(function(a){f=arguments,g.html(d?n("<div>").append(n.parseHTML(a)).find(d):a)}).always(c&&function(a,b){g.each(function(){c.apply(this,f||[a.responseText,b,a])})}),this},n.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){n.fn[b]=function(a){return this.on(b,a)}}),n.expr.filters.animated=function(a){return n.grep(n.timers,function(b){return a===b.elem}).length};function Mb(a){return n.isWindow(a)?a:9===a.nodeType&&a.defaultView}n.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=n.css(a,"position"),l=n(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=n.css(a,"top"),i=n.css(a,"left"),j=("absolute"===k||"fixed"===k)&&(f+i).indexOf("auto")>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),n.isFunction(b)&&(b=b.call(a,c,n.extend({},h))),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},n.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){n.offset.setOffset(this,a,b)});var b,c,d=this[0],e={top:0,left:0},f=d&&d.ownerDocument;if(f)return b=f.documentElement,n.contains(b,d)?(e=d.getBoundingClientRect(),c=Mb(f),{top:e.top+c.pageYOffset-b.clientTop,left:e.left+c.pageXOffset-b.clientLeft}):e},position:function(){if(this[0]){var a,b,c=this[0],d={top:0,left:0};return"fixed"===n.css(c,"position")?b=c.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),n.nodeName(a[0],"html")||(d=a.offset()),d.top+=n.css(a[0],"borderTopWidth",!0),d.left+=n.css(a[0],"borderLeftWidth",!0)),{top:b.top-d.top-n.css(c,"marginTop",!0),left:b.left-d.left-n.css(c,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent;while(a&&"static"===n.css(a,"position"))a=a.offsetParent;return a||Ea})}}),n.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c="pageYOffset"===b;n.fn[a]=function(d){return K(this,function(a,d,e){var f=Mb(a);return void 0===e?f?f[b]:a[d]:void(f?f.scrollTo(c?f.pageXOffset:e,c?e:f.pageYOffset):a[d]=e)},a,d,arguments.length)}}),n.each(["top","left"],function(a,b){n.cssHooks[b]=Ga(l.pixelPosition,function(a,c){return c?(c=Fa(a,b),Ba.test(c)?n(a).position()[b]+"px":c):void 0})}),n.each({Height:"height",Width:"width"},function(a,b){n.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){n.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return K(this,function(b,c,d){var e;return n.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?n.css(b,c,g):n.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),n.fn.extend({bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)},size:function(){return this.length}}),n.fn.andSelf=n.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return n});var Nb=a.jQuery,Ob=a.$;return n.noConflict=function(b){return a.$===n&&(a.$=Ob),b&&a.jQuery===n&&(a.jQuery=Nb),n},b||(a.jQuery=a.$=n),n});
;
/*! jQuery UI - v1.12.1 - 2016-09-14
* http://jqueryui.com
* Includes: widget.js, position.js, data.js, disable-selection.js, effect.js, effects/effect-blind.js, effects/effect-bounce.js, effects/effect-clip.js, effects/effect-drop.js, effects/effect-explode.js, effects/effect-fade.js, effects/effect-fold.js, effects/effect-highlight.js, effects/effect-puff.js, effects/effect-pulsate.js, effects/effect-scale.js, effects/effect-shake.js, effects/effect-size.js, effects/effect-slide.js, effects/effect-transfer.js, focusable.js, form-reset-mixin.js, jquery-1-7.js, keycode.js, labels.js, scroll-parent.js, tabbable.js, unique-id.js, widgets/accordion.js, widgets/autocomplete.js, widgets/button.js, widgets/checkboxradio.js, widgets/controlgroup.js, widgets/datepicker.js, widgets/dialog.js, widgets/draggable.js, widgets/droppable.js, widgets/menu.js, widgets/mouse.js, widgets/progressbar.js, widgets/resizable.js, widgets/selectable.js, widgets/selectmenu.js, widgets/slider.js, widgets/sortable.js, widgets/spinner.js, widgets/tabs.js, widgets/tooltip.js
* Copyright jQuery Foundation and other contributors; Licensed MIT */

(function(t){"function"==typeof define&&define.amd?define(["jquery"],t):t(jQuery)})(function(t){function e(t){for(var e=t.css("visibility");"inherit"===e;)t=t.parent(),e=t.css("visibility");return"hidden"!==e}function i(t){for(var e,i;t.length&&t[0]!==document;){if(e=t.css("position"),("absolute"===e||"relative"===e||"fixed"===e)&&(i=parseInt(t.css("zIndex"),10),!isNaN(i)&&0!==i))return i;t=t.parent()}return 0}function s(){this._curInst=null,this._keyEvent=!1,this._disabledInputs=[],this._datepickerShowing=!1,this._inDialog=!1,this._mainDivId="ui-datepicker-div",this._inlineClass="ui-datepicker-inline",this._appendClass="ui-datepicker-append",this._triggerClass="ui-datepicker-trigger",this._dialogClass="ui-datepicker-dialog",this._disableClass="ui-datepicker-disabled",this._unselectableClass="ui-datepicker-unselectable",this._currentClass="ui-datepicker-current-day",this._dayOverClass="ui-datepicker-days-cell-over",this.regional=[],this.regional[""]={closeText:"Done",prevText:"Prev",nextText:"Next",currentText:"Today",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],weekHeader:"Wk",dateFormat:"mm/dd/yy",firstDay:0,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},this._defaults={showOn:"focus",showAnim:"fadeIn",showOptions:{},defaultDate:null,appendText:"",buttonText:"...",buttonImage:"",buttonImageOnly:!1,hideIfNoPrevNext:!1,navigationAsDateFormat:!1,gotoCurrent:!1,changeMonth:!1,changeYear:!1,yearRange:"c-10:c+10",showOtherMonths:!1,selectOtherMonths:!1,showWeek:!1,calculateWeek:this.iso8601Week,shortYearCutoff:"+10",minDate:null,maxDate:null,duration:"fast",beforeShowDay:null,beforeShow:null,onSelect:null,onChangeMonthYear:null,onClose:null,numberOfMonths:1,showCurrentAtPos:0,stepMonths:1,stepBigMonths:12,altField:"",altFormat:"",constrainInput:!0,showButtonPanel:!1,autoSize:!1,disabled:!1},t.extend(this._defaults,this.regional[""]),this.regional.en=t.extend(!0,{},this.regional[""]),this.regional["en-US"]=t.extend(!0,{},this.regional.en),this.dpDiv=n(t("<div id='"+this._mainDivId+"' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>"))}function n(e){var i="button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";return e.on("mouseout",i,function(){t(this).removeClass("ui-state-hover"),-1!==this.className.indexOf("ui-datepicker-prev")&&t(this).removeClass("ui-datepicker-prev-hover"),-1!==this.className.indexOf("ui-datepicker-next")&&t(this).removeClass("ui-datepicker-next-hover")}).on("mouseover",i,o)}function o(){t.datepicker._isDisabledDatepicker(m.inline?m.dpDiv.parent()[0]:m.input[0])||(t(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover"),t(this).addClass("ui-state-hover"),-1!==this.className.indexOf("ui-datepicker-prev")&&t(this).addClass("ui-datepicker-prev-hover"),-1!==this.className.indexOf("ui-datepicker-next")&&t(this).addClass("ui-datepicker-next-hover"))}function a(e,i){t.extend(e,i);for(var s in i)null==i[s]&&(e[s]=i[s]);return e}function r(t){return function(){var e=this.element.val();t.apply(this,arguments),this._refresh(),e!==this.element.val()&&this._trigger("change")}}t.ui=t.ui||{},t.ui.version="1.12.1";var h=0,l=Array.prototype.slice;t.cleanData=function(e){return function(i){var s,n,o;for(o=0;null!=(n=i[o]);o++)try{s=t._data(n,"events"),s&&s.remove&&t(n).triggerHandler("remove")}catch(a){}e(i)}}(t.cleanData),t.widget=function(e,i,s){var n,o,a,r={},h=e.split(".")[0];e=e.split(".")[1];var l=h+"-"+e;return s||(s=i,i=t.Widget),t.isArray(s)&&(s=t.extend.apply(null,[{}].concat(s))),t.expr[":"][l.toLowerCase()]=function(e){return!!t.data(e,l)},t[h]=t[h]||{},n=t[h][e],o=t[h][e]=function(t,e){return this._createWidget?(arguments.length&&this._createWidget(t,e),void 0):new o(t,e)},t.extend(o,n,{version:s.version,_proto:t.extend({},s),_childConstructors:[]}),a=new i,a.options=t.widget.extend({},a.options),t.each(s,function(e,s){return t.isFunction(s)?(r[e]=function(){function t(){return i.prototype[e].apply(this,arguments)}function n(t){return i.prototype[e].apply(this,t)}return function(){var e,i=this._super,o=this._superApply;return this._super=t,this._superApply=n,e=s.apply(this,arguments),this._super=i,this._superApply=o,e}}(),void 0):(r[e]=s,void 0)}),o.prototype=t.widget.extend(a,{widgetEventPrefix:n?a.widgetEventPrefix||e:e},r,{constructor:o,namespace:h,widgetName:e,widgetFullName:l}),n?(t.each(n._childConstructors,function(e,i){var s=i.prototype;t.widget(s.namespace+"."+s.widgetName,o,i._proto)}),delete n._childConstructors):i._childConstructors.push(o),t.widget.bridge(e,o),o},t.widget.extend=function(e){for(var i,s,n=l.call(arguments,1),o=0,a=n.length;a>o;o++)for(i in n[o])s=n[o][i],n[o].hasOwnProperty(i)&&void 0!==s&&(e[i]=t.isPlainObject(s)?t.isPlainObject(e[i])?t.widget.extend({},e[i],s):t.widget.extend({},s):s);return e},t.widget.bridge=function(e,i){var s=i.prototype.widgetFullName||e;t.fn[e]=function(n){var o="string"==typeof n,a=l.call(arguments,1),r=this;return o?this.length||"instance"!==n?this.each(function(){var i,o=t.data(this,s);return"instance"===n?(r=o,!1):o?t.isFunction(o[n])&&"_"!==n.charAt(0)?(i=o[n].apply(o,a),i!==o&&void 0!==i?(r=i&&i.jquery?r.pushStack(i.get()):i,!1):void 0):t.error("no such method '"+n+"' for "+e+" widget instance"):t.error("cannot call methods on "+e+" prior to initialization; "+"attempted to call method '"+n+"'")}):r=void 0:(a.length&&(n=t.widget.extend.apply(null,[n].concat(a))),this.each(function(){var e=t.data(this,s);e?(e.option(n||{}),e._init&&e._init()):t.data(this,s,new i(n,this))})),r}},t.Widget=function(){},t.Widget._childConstructors=[],t.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"<div>",options:{classes:{},disabled:!1,create:null},_createWidget:function(e,i){i=t(i||this.defaultElement||this)[0],this.element=t(i),this.uuid=h++,this.eventNamespace="."+this.widgetName+this.uuid,this.bindings=t(),this.hoverable=t(),this.focusable=t(),this.classesElementLookup={},i!==this&&(t.data(i,this.widgetFullName,this),this._on(!0,this.element,{remove:function(t){t.target===i&&this.destroy()}}),this.document=t(i.style?i.ownerDocument:i.document||i),this.window=t(this.document[0].defaultView||this.document[0].parentWindow)),this.options=t.widget.extend({},this.options,this._getCreateOptions(),e),this._create(),this.options.disabled&&this._setOptionDisabled(this.options.disabled),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:function(){return{}},_getCreateEventData:t.noop,_create:t.noop,_init:t.noop,destroy:function(){var e=this;this._destroy(),t.each(this.classesElementLookup,function(t,i){e._removeClass(i,t)}),this.element.off(this.eventNamespace).removeData(this.widgetFullName),this.widget().off(this.eventNamespace).removeAttr("aria-disabled"),this.bindings.off(this.eventNamespace)},_destroy:t.noop,widget:function(){return this.element},option:function(e,i){var s,n,o,a=e;if(0===arguments.length)return t.widget.extend({},this.options);if("string"==typeof e)if(a={},s=e.split("."),e=s.shift(),s.length){for(n=a[e]=t.widget.extend({},this.options[e]),o=0;s.length-1>o;o++)n[s[o]]=n[s[o]]||{},n=n[s[o]];if(e=s.pop(),1===arguments.length)return void 0===n[e]?null:n[e];n[e]=i}else{if(1===arguments.length)return void 0===this.options[e]?null:this.options[e];a[e]=i}return this._setOptions(a),this},_setOptions:function(t){var e;for(e in t)this._setOption(e,t[e]);return this},_setOption:function(t,e){return"classes"===t&&this._setOptionClasses(e),this.options[t]=e,"disabled"===t&&this._setOptionDisabled(e),this},_setOptionClasses:function(e){var i,s,n;for(i in e)n=this.classesElementLookup[i],e[i]!==this.options.classes[i]&&n&&n.length&&(s=t(n.get()),this._removeClass(n,i),s.addClass(this._classes({element:s,keys:i,classes:e,add:!0})))},_setOptionDisabled:function(t){this._toggleClass(this.widget(),this.widgetFullName+"-disabled",null,!!t),t&&(this._removeClass(this.hoverable,null,"ui-state-hover"),this._removeClass(this.focusable,null,"ui-state-focus"))},enable:function(){return this._setOptions({disabled:!1})},disable:function(){return this._setOptions({disabled:!0})},_classes:function(e){function i(i,o){var a,r;for(r=0;i.length>r;r++)a=n.classesElementLookup[i[r]]||t(),a=e.add?t(t.unique(a.get().concat(e.element.get()))):t(a.not(e.element).get()),n.classesElementLookup[i[r]]=a,s.push(i[r]),o&&e.classes[i[r]]&&s.push(e.classes[i[r]])}var s=[],n=this;return e=t.extend({element:this.element,classes:this.options.classes||{}},e),this._on(e.element,{remove:"_untrackClassesElement"}),e.keys&&i(e.keys.match(/\S+/g)||[],!0),e.extra&&i(e.extra.match(/\S+/g)||[]),s.join(" ")},_untrackClassesElement:function(e){var i=this;t.each(i.classesElementLookup,function(s,n){-1!==t.inArray(e.target,n)&&(i.classesElementLookup[s]=t(n.not(e.target).get()))})},_removeClass:function(t,e,i){return this._toggleClass(t,e,i,!1)},_addClass:function(t,e,i){return this._toggleClass(t,e,i,!0)},_toggleClass:function(t,e,i,s){s="boolean"==typeof s?s:i;var n="string"==typeof t||null===t,o={extra:n?e:i,keys:n?t:e,element:n?this.element:t,add:s};return o.element.toggleClass(this._classes(o),s),this},_on:function(e,i,s){var n,o=this;"boolean"!=typeof e&&(s=i,i=e,e=!1),s?(i=n=t(i),this.bindings=this.bindings.add(i)):(s=i,i=this.element,n=this.widget()),t.each(s,function(s,a){function r(){return e||o.options.disabled!==!0&&!t(this).hasClass("ui-state-disabled")?("string"==typeof a?o[a]:a).apply(o,arguments):void 0}"string"!=typeof a&&(r.guid=a.guid=a.guid||r.guid||t.guid++);var h=s.match(/^([\w:-]*)\s*(.*)$/),l=h[1]+o.eventNamespace,c=h[2];c?n.on(l,c,r):i.on(l,r)})},_off:function(e,i){i=(i||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace,e.off(i).off(i),this.bindings=t(this.bindings.not(e).get()),this.focusable=t(this.focusable.not(e).get()),this.hoverable=t(this.hoverable.not(e).get())},_delay:function(t,e){function i(){return("string"==typeof t?s[t]:t).apply(s,arguments)}var s=this;return setTimeout(i,e||0)},_hoverable:function(e){this.hoverable=this.hoverable.add(e),this._on(e,{mouseenter:function(e){this._addClass(t(e.currentTarget),null,"ui-state-hover")},mouseleave:function(e){this._removeClass(t(e.currentTarget),null,"ui-state-hover")}})},_focusable:function(e){this.focusable=this.focusable.add(e),this._on(e,{focusin:function(e){this._addClass(t(e.currentTarget),null,"ui-state-focus")},focusout:function(e){this._removeClass(t(e.currentTarget),null,"ui-state-focus")}})},_trigger:function(e,i,s){var n,o,a=this.options[e];if(s=s||{},i=t.Event(i),i.type=(e===this.widgetEventPrefix?e:this.widgetEventPrefix+e).toLowerCase(),i.target=this.element[0],o=i.originalEvent)for(n in o)n in i||(i[n]=o[n]);return this.element.trigger(i,s),!(t.isFunction(a)&&a.apply(this.element[0],[i].concat(s))===!1||i.isDefaultPrevented())}},t.each({show:"fadeIn",hide:"fadeOut"},function(e,i){t.Widget.prototype["_"+e]=function(s,n,o){"string"==typeof n&&(n={effect:n});var a,r=n?n===!0||"number"==typeof n?i:n.effect||i:e;n=n||{},"number"==typeof n&&(n={duration:n}),a=!t.isEmptyObject(n),n.complete=o,n.delay&&s.delay(n.delay),a&&t.effects&&t.effects.effect[r]?s[e](n):r!==e&&s[r]?s[r](n.duration,n.easing,o):s.queue(function(i){t(this)[e](),o&&o.call(s[0]),i()})}}),t.widget,function(){function e(t,e,i){return[parseFloat(t[0])*(u.test(t[0])?e/100:1),parseFloat(t[1])*(u.test(t[1])?i/100:1)]}function i(e,i){return parseInt(t.css(e,i),10)||0}function s(e){var i=e[0];return 9===i.nodeType?{width:e.width(),height:e.height(),offset:{top:0,left:0}}:t.isWindow(i)?{width:e.width(),height:e.height(),offset:{top:e.scrollTop(),left:e.scrollLeft()}}:i.preventDefault?{width:0,height:0,offset:{top:i.pageY,left:i.pageX}}:{width:e.outerWidth(),height:e.outerHeight(),offset:e.offset()}}var n,o=Math.max,a=Math.abs,r=/left|center|right/,h=/top|center|bottom/,l=/[\+\-]\d+(\.[\d]+)?%?/,c=/^\w+/,u=/%$/,d=t.fn.position;t.position={scrollbarWidth:function(){if(void 0!==n)return n;var e,i,s=t("<div style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>"),o=s.children()[0];return t("body").append(s),e=o.offsetWidth,s.css("overflow","scroll"),i=o.offsetWidth,e===i&&(i=s[0].clientWidth),s.remove(),n=e-i},getScrollInfo:function(e){var i=e.isWindow||e.isDocument?"":e.element.css("overflow-x"),s=e.isWindow||e.isDocument?"":e.element.css("overflow-y"),n="scroll"===i||"auto"===i&&e.width<e.element[0].scrollWidth,o="scroll"===s||"auto"===s&&e.height<e.element[0].scrollHeight;return{width:o?t.position.scrollbarWidth():0,height:n?t.position.scrollbarWidth():0}},getWithinInfo:function(e){var i=t(e||window),s=t.isWindow(i[0]),n=!!i[0]&&9===i[0].nodeType,o=!s&&!n;return{element:i,isWindow:s,isDocument:n,offset:o?t(e).offset():{left:0,top:0},scrollLeft:i.scrollLeft(),scrollTop:i.scrollTop(),width:i.outerWidth(),height:i.outerHeight()}}},t.fn.position=function(n){if(!n||!n.of)return d.apply(this,arguments);n=t.extend({},n);var u,p,f,g,m,_,v=t(n.of),b=t.position.getWithinInfo(n.within),y=t.position.getScrollInfo(b),w=(n.collision||"flip").split(" "),k={};return _=s(v),v[0].preventDefault&&(n.at="left top"),p=_.width,f=_.height,g=_.offset,m=t.extend({},g),t.each(["my","at"],function(){var t,e,i=(n[this]||"").split(" ");1===i.length&&(i=r.test(i[0])?i.concat(["center"]):h.test(i[0])?["center"].concat(i):["center","center"]),i[0]=r.test(i[0])?i[0]:"center",i[1]=h.test(i[1])?i[1]:"center",t=l.exec(i[0]),e=l.exec(i[1]),k[this]=[t?t[0]:0,e?e[0]:0],n[this]=[c.exec(i[0])[0],c.exec(i[1])[0]]}),1===w.length&&(w[1]=w[0]),"right"===n.at[0]?m.left+=p:"center"===n.at[0]&&(m.left+=p/2),"bottom"===n.at[1]?m.top+=f:"center"===n.at[1]&&(m.top+=f/2),u=e(k.at,p,f),m.left+=u[0],m.top+=u[1],this.each(function(){var s,r,h=t(this),l=h.outerWidth(),c=h.outerHeight(),d=i(this,"marginLeft"),_=i(this,"marginTop"),x=l+d+i(this,"marginRight")+y.width,C=c+_+i(this,"marginBottom")+y.height,D=t.extend({},m),I=e(k.my,h.outerWidth(),h.outerHeight());"right"===n.my[0]?D.left-=l:"center"===n.my[0]&&(D.left-=l/2),"bottom"===n.my[1]?D.top-=c:"center"===n.my[1]&&(D.top-=c/2),D.left+=I[0],D.top+=I[1],s={marginLeft:d,marginTop:_},t.each(["left","top"],function(e,i){t.ui.position[w[e]]&&t.ui.position[w[e]][i](D,{targetWidth:p,targetHeight:f,elemWidth:l,elemHeight:c,collisionPosition:s,collisionWidth:x,collisionHeight:C,offset:[u[0]+I[0],u[1]+I[1]],my:n.my,at:n.at,within:b,elem:h})}),n.using&&(r=function(t){var e=g.left-D.left,i=e+p-l,s=g.top-D.top,r=s+f-c,u={target:{element:v,left:g.left,top:g.top,width:p,height:f},element:{element:h,left:D.left,top:D.top,width:l,height:c},horizontal:0>i?"left":e>0?"right":"center",vertical:0>r?"top":s>0?"bottom":"middle"};l>p&&p>a(e+i)&&(u.horizontal="center"),c>f&&f>a(s+r)&&(u.vertical="middle"),u.important=o(a(e),a(i))>o(a(s),a(r))?"horizontal":"vertical",n.using.call(this,t,u)}),h.offset(t.extend(D,{using:r}))})},t.ui.position={fit:{left:function(t,e){var i,s=e.within,n=s.isWindow?s.scrollLeft:s.offset.left,a=s.width,r=t.left-e.collisionPosition.marginLeft,h=n-r,l=r+e.collisionWidth-a-n;e.collisionWidth>a?h>0&&0>=l?(i=t.left+h+e.collisionWidth-a-n,t.left+=h-i):t.left=l>0&&0>=h?n:h>l?n+a-e.collisionWidth:n:h>0?t.left+=h:l>0?t.left-=l:t.left=o(t.left-r,t.left)},top:function(t,e){var i,s=e.within,n=s.isWindow?s.scrollTop:s.offset.top,a=e.within.height,r=t.top-e.collisionPosition.marginTop,h=n-r,l=r+e.collisionHeight-a-n;e.collisionHeight>a?h>0&&0>=l?(i=t.top+h+e.collisionHeight-a-n,t.top+=h-i):t.top=l>0&&0>=h?n:h>l?n+a-e.collisionHeight:n:h>0?t.top+=h:l>0?t.top-=l:t.top=o(t.top-r,t.top)}},flip:{left:function(t,e){var i,s,n=e.within,o=n.offset.left+n.scrollLeft,r=n.width,h=n.isWindow?n.scrollLeft:n.offset.left,l=t.left-e.collisionPosition.marginLeft,c=l-h,u=l+e.collisionWidth-r-h,d="left"===e.my[0]?-e.elemWidth:"right"===e.my[0]?e.elemWidth:0,p="left"===e.at[0]?e.targetWidth:"right"===e.at[0]?-e.targetWidth:0,f=-2*e.offset[0];0>c?(i=t.left+d+p+f+e.collisionWidth-r-o,(0>i||a(c)>i)&&(t.left+=d+p+f)):u>0&&(s=t.left-e.collisionPosition.marginLeft+d+p+f-h,(s>0||u>a(s))&&(t.left+=d+p+f))},top:function(t,e){var i,s,n=e.within,o=n.offset.top+n.scrollTop,r=n.height,h=n.isWindow?n.scrollTop:n.offset.top,l=t.top-e.collisionPosition.marginTop,c=l-h,u=l+e.collisionHeight-r-h,d="top"===e.my[1],p=d?-e.elemHeight:"bottom"===e.my[1]?e.elemHeight:0,f="top"===e.at[1]?e.targetHeight:"bottom"===e.at[1]?-e.targetHeight:0,g=-2*e.offset[1];0>c?(s=t.top+p+f+g+e.collisionHeight-r-o,(0>s||a(c)>s)&&(t.top+=p+f+g)):u>0&&(i=t.top-e.collisionPosition.marginTop+p+f+g-h,(i>0||u>a(i))&&(t.top+=p+f+g))}},flipfit:{left:function(){t.ui.position.flip.left.apply(this,arguments),t.ui.position.fit.left.apply(this,arguments)},top:function(){t.ui.position.flip.top.apply(this,arguments),t.ui.position.fit.top.apply(this,arguments)}}}}(),t.ui.position,t.extend(t.expr[":"],{data:t.expr.createPseudo?t.expr.createPseudo(function(e){return function(i){return!!t.data(i,e)}}):function(e,i,s){return!!t.data(e,s[3])}}),t.fn.extend({disableSelection:function(){var t="onselectstart"in document.createElement("div")?"selectstart":"mousedown";return function(){return this.on(t+".ui-disableSelection",function(t){t.preventDefault()})}}(),enableSelection:function(){return this.off(".ui-disableSelection")}});var c="ui-effects-",u="ui-effects-style",d="ui-effects-animated",p=t;t.effects={effect:{}},function(t,e){function i(t,e,i){var s=u[e.type]||{};return null==t?i||!e.def?null:e.def:(t=s.floor?~~t:parseFloat(t),isNaN(t)?e.def:s.mod?(t+s.mod)%s.mod:0>t?0:t>s.max?s.max:t)}function s(i){var s=l(),n=s._rgba=[];return i=i.toLowerCase(),f(h,function(t,o){var a,r=o.re.exec(i),h=r&&o.parse(r),l=o.space||"rgba";return h?(a=s[l](h),s[c[l].cache]=a[c[l].cache],n=s._rgba=a._rgba,!1):e}),n.length?("0,0,0,0"===n.join()&&t.extend(n,o.transparent),s):o[i]}function n(t,e,i){return i=(i+1)%1,1>6*i?t+6*(e-t)*i:1>2*i?e:2>3*i?t+6*(e-t)*(2/3-i):t}var o,a="backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor",r=/^([\-+])=\s*(\d+\.?\d*)/,h=[{re:/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,parse:function(t){return[t[1],t[2],t[3],t[4]]}},{re:/rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,parse:function(t){return[2.55*t[1],2.55*t[2],2.55*t[3],t[4]]}},{re:/#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/,parse:function(t){return[parseInt(t[1],16),parseInt(t[2],16),parseInt(t[3],16)]}},{re:/#([a-f0-9])([a-f0-9])([a-f0-9])/,parse:function(t){return[parseInt(t[1]+t[1],16),parseInt(t[2]+t[2],16),parseInt(t[3]+t[3],16)]}},{re:/hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,space:"hsla",parse:function(t){return[t[1],t[2]/100,t[3]/100,t[4]]}}],l=t.Color=function(e,i,s,n){return new t.Color.fn.parse(e,i,s,n)},c={rgba:{props:{red:{idx:0,type:"byte"},green:{idx:1,type:"byte"},blue:{idx:2,type:"byte"}}},hsla:{props:{hue:{idx:0,type:"degrees"},saturation:{idx:1,type:"percent"},lightness:{idx:2,type:"percent"}}}},u={"byte":{floor:!0,max:255},percent:{max:1},degrees:{mod:360,floor:!0}},d=l.support={},p=t("<p>")[0],f=t.each;p.style.cssText="background-color:rgba(1,1,1,.5)",d.rgba=p.style.backgroundColor.indexOf("rgba")>-1,f(c,function(t,e){e.cache="_"+t,e.props.alpha={idx:3,type:"percent",def:1}}),l.fn=t.extend(l.prototype,{parse:function(n,a,r,h){if(n===e)return this._rgba=[null,null,null,null],this;(n.jquery||n.nodeType)&&(n=t(n).css(a),a=e);var u=this,d=t.type(n),p=this._rgba=[];return a!==e&&(n=[n,a,r,h],d="array"),"string"===d?this.parse(s(n)||o._default):"array"===d?(f(c.rgba.props,function(t,e){p[e.idx]=i(n[e.idx],e)}),this):"object"===d?(n instanceof l?f(c,function(t,e){n[e.cache]&&(u[e.cache]=n[e.cache].slice())}):f(c,function(e,s){var o=s.cache;f(s.props,function(t,e){if(!u[o]&&s.to){if("alpha"===t||null==n[t])return;u[o]=s.to(u._rgba)}u[o][e.idx]=i(n[t],e,!0)}),u[o]&&0>t.inArray(null,u[o].slice(0,3))&&(u[o][3]=1,s.from&&(u._rgba=s.from(u[o])))}),this):e},is:function(t){var i=l(t),s=!0,n=this;return f(c,function(t,o){var a,r=i[o.cache];return r&&(a=n[o.cache]||o.to&&o.to(n._rgba)||[],f(o.props,function(t,i){return null!=r[i.idx]?s=r[i.idx]===a[i.idx]:e})),s}),s},_space:function(){var t=[],e=this;return f(c,function(i,s){e[s.cache]&&t.push(i)}),t.pop()},transition:function(t,e){var s=l(t),n=s._space(),o=c[n],a=0===this.alpha()?l("transparent"):this,r=a[o.cache]||o.to(a._rgba),h=r.slice();return s=s[o.cache],f(o.props,function(t,n){var o=n.idx,a=r[o],l=s[o],c=u[n.type]||{};null!==l&&(null===a?h[o]=l:(c.mod&&(l-a>c.mod/2?a+=c.mod:a-l>c.mod/2&&(a-=c.mod)),h[o]=i((l-a)*e+a,n)))}),this[n](h)},blend:function(e){if(1===this._rgba[3])return this;var i=this._rgba.slice(),s=i.pop(),n=l(e)._rgba;return l(t.map(i,function(t,e){return(1-s)*n[e]+s*t}))},toRgbaString:function(){var e="rgba(",i=t.map(this._rgba,function(t,e){return null==t?e>2?1:0:t});return 1===i[3]&&(i.pop(),e="rgb("),e+i.join()+")"},toHslaString:function(){var e="hsla(",i=t.map(this.hsla(),function(t,e){return null==t&&(t=e>2?1:0),e&&3>e&&(t=Math.round(100*t)+"%"),t});return 1===i[3]&&(i.pop(),e="hsl("),e+i.join()+")"},toHexString:function(e){var i=this._rgba.slice(),s=i.pop();return e&&i.push(~~(255*s)),"#"+t.map(i,function(t){return t=(t||0).toString(16),1===t.length?"0"+t:t}).join("")},toString:function(){return 0===this._rgba[3]?"transparent":this.toRgbaString()}}),l.fn.parse.prototype=l.fn,c.hsla.to=function(t){if(null==t[0]||null==t[1]||null==t[2])return[null,null,null,t[3]];var e,i,s=t[0]/255,n=t[1]/255,o=t[2]/255,a=t[3],r=Math.max(s,n,o),h=Math.min(s,n,o),l=r-h,c=r+h,u=.5*c;return e=h===r?0:s===r?60*(n-o)/l+360:n===r?60*(o-s)/l+120:60*(s-n)/l+240,i=0===l?0:.5>=u?l/c:l/(2-c),[Math.round(e)%360,i,u,null==a?1:a]},c.hsla.from=function(t){if(null==t[0]||null==t[1]||null==t[2])return[null,null,null,t[3]];var e=t[0]/360,i=t[1],s=t[2],o=t[3],a=.5>=s?s*(1+i):s+i-s*i,r=2*s-a;return[Math.round(255*n(r,a,e+1/3)),Math.round(255*n(r,a,e)),Math.round(255*n(r,a,e-1/3)),o]},f(c,function(s,n){var o=n.props,a=n.cache,h=n.to,c=n.from;l.fn[s]=function(s){if(h&&!this[a]&&(this[a]=h(this._rgba)),s===e)return this[a].slice();var n,r=t.type(s),u="array"===r||"object"===r?s:arguments,d=this[a].slice();return f(o,function(t,e){var s=u["object"===r?t:e.idx];null==s&&(s=d[e.idx]),d[e.idx]=i(s,e)}),c?(n=l(c(d)),n[a]=d,n):l(d)},f(o,function(e,i){l.fn[e]||(l.fn[e]=function(n){var o,a=t.type(n),h="alpha"===e?this._hsla?"hsla":"rgba":s,l=this[h](),c=l[i.idx];return"undefined"===a?c:("function"===a&&(n=n.call(this,c),a=t.type(n)),null==n&&i.empty?this:("string"===a&&(o=r.exec(n),o&&(n=c+parseFloat(o[2])*("+"===o[1]?1:-1))),l[i.idx]=n,this[h](l)))})})}),l.hook=function(e){var i=e.split(" ");f(i,function(e,i){t.cssHooks[i]={set:function(e,n){var o,a,r="";if("transparent"!==n&&("string"!==t.type(n)||(o=s(n)))){if(n=l(o||n),!d.rgba&&1!==n._rgba[3]){for(a="backgroundColor"===i?e.parentNode:e;(""===r||"transparent"===r)&&a&&a.style;)try{r=t.css(a,"backgroundColor"),a=a.parentNode}catch(h){}n=n.blend(r&&"transparent"!==r?r:"_default")}n=n.toRgbaString()}try{e.style[i]=n}catch(h){}}},t.fx.step[i]=function(e){e.colorInit||(e.start=l(e.elem,i),e.end=l(e.end),e.colorInit=!0),t.cssHooks[i].set(e.elem,e.start.transition(e.end,e.pos))}})},l.hook(a),t.cssHooks.borderColor={expand:function(t){var e={};return f(["Top","Right","Bottom","Left"],function(i,s){e["border"+s+"Color"]=t}),e}},o=t.Color.names={aqua:"#00ffff",black:"#000000",blue:"#0000ff",fuchsia:"#ff00ff",gray:"#808080",green:"#008000",lime:"#00ff00",maroon:"#800000",navy:"#000080",olive:"#808000",purple:"#800080",red:"#ff0000",silver:"#c0c0c0",teal:"#008080",white:"#ffffff",yellow:"#ffff00",transparent:[null,null,null,0],_default:"#ffffff"}}(p),function(){function e(e){var i,s,n=e.ownerDocument.defaultView?e.ownerDocument.defaultView.getComputedStyle(e,null):e.currentStyle,o={};if(n&&n.length&&n[0]&&n[n[0]])for(s=n.length;s--;)i=n[s],"string"==typeof n[i]&&(o[t.camelCase(i)]=n[i]);else for(i in n)"string"==typeof n[i]&&(o[i]=n[i]);return o}function i(e,i){var s,o,a={};for(s in i)o=i[s],e[s]!==o&&(n[s]||(t.fx.step[s]||!isNaN(parseFloat(o)))&&(a[s]=o));return a}var s=["add","remove","toggle"],n={border:1,borderBottom:1,borderColor:1,borderLeft:1,borderRight:1,borderTop:1,borderWidth:1,margin:1,padding:1};t.each(["borderLeftStyle","borderRightStyle","borderBottomStyle","borderTopStyle"],function(e,i){t.fx.step[i]=function(t){("none"!==t.end&&!t.setAttr||1===t.pos&&!t.setAttr)&&(p.style(t.elem,i,t.end),t.setAttr=!0)}}),t.fn.addBack||(t.fn.addBack=function(t){return this.add(null==t?this.prevObject:this.prevObject.filter(t))}),t.effects.animateClass=function(n,o,a,r){var h=t.speed(o,a,r);return this.queue(function(){var o,a=t(this),r=a.attr("class")||"",l=h.children?a.find("*").addBack():a;l=l.map(function(){var i=t(this);return{el:i,start:e(this)}}),o=function(){t.each(s,function(t,e){n[e]&&a[e+"Class"](n[e])})},o(),l=l.map(function(){return this.end=e(this.el[0]),this.diff=i(this.start,this.end),this}),a.attr("class",r),l=l.map(function(){var e=this,i=t.Deferred(),s=t.extend({},h,{queue:!1,complete:function(){i.resolve(e)}});return this.el.animate(this.diff,s),i.promise()}),t.when.apply(t,l.get()).done(function(){o(),t.each(arguments,function(){var e=this.el;t.each(this.diff,function(t){e.css(t,"")})}),h.complete.call(a[0])})})},t.fn.extend({addClass:function(e){return function(i,s,n,o){return s?t.effects.animateClass.call(this,{add:i},s,n,o):e.apply(this,arguments)}}(t.fn.addClass),removeClass:function(e){return function(i,s,n,o){return arguments.length>1?t.effects.animateClass.call(this,{remove:i},s,n,o):e.apply(this,arguments)}}(t.fn.removeClass),toggleClass:function(e){return function(i,s,n,o,a){return"boolean"==typeof s||void 0===s?n?t.effects.animateClass.call(this,s?{add:i}:{remove:i},n,o,a):e.apply(this,arguments):t.effects.animateClass.call(this,{toggle:i},s,n,o)}}(t.fn.toggleClass),switchClass:function(e,i,s,n,o){return t.effects.animateClass.call(this,{add:i,remove:e},s,n,o)}})}(),function(){function e(e,i,s,n){return t.isPlainObject(e)&&(i=e,e=e.effect),e={effect:e},null==i&&(i={}),t.isFunction(i)&&(n=i,s=null,i={}),("number"==typeof i||t.fx.speeds[i])&&(n=s,s=i,i={}),t.isFunction(s)&&(n=s,s=null),i&&t.extend(e,i),s=s||i.duration,e.duration=t.fx.off?0:"number"==typeof s?s:s in t.fx.speeds?t.fx.speeds[s]:t.fx.speeds._default,e.complete=n||i.complete,e}function i(e){return!e||"number"==typeof e||t.fx.speeds[e]?!0:"string"!=typeof e||t.effects.effect[e]?t.isFunction(e)?!0:"object"!=typeof e||e.effect?!1:!0:!0}function s(t,e){var i=e.outerWidth(),s=e.outerHeight(),n=/^rect\((-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto)\)$/,o=n.exec(t)||["",0,i,s,0];return{top:parseFloat(o[1])||0,right:"auto"===o[2]?i:parseFloat(o[2]),bottom:"auto"===o[3]?s:parseFloat(o[3]),left:parseFloat(o[4])||0}}t.expr&&t.expr.filters&&t.expr.filters.animated&&(t.expr.filters.animated=function(e){return function(i){return!!t(i).data(d)||e(i)}}(t.expr.filters.animated)),t.uiBackCompat!==!1&&t.extend(t.effects,{save:function(t,e){for(var i=0,s=e.length;s>i;i++)null!==e[i]&&t.data(c+e[i],t[0].style[e[i]])},restore:function(t,e){for(var i,s=0,n=e.length;n>s;s++)null!==e[s]&&(i=t.data(c+e[s]),t.css(e[s],i))},setMode:function(t,e){return"toggle"===e&&(e=t.is(":hidden")?"show":"hide"),e},createWrapper:function(e){if(e.parent().is(".ui-effects-wrapper"))return e.parent();var i={width:e.outerWidth(!0),height:e.outerHeight(!0),"float":e.css("float")},s=t("<div></div>").addClass("ui-effects-wrapper").css({fontSize:"100%",background:"transparent",border:"none",margin:0,padding:0}),n={width:e.width(),height:e.height()},o=document.activeElement;try{o.id}catch(a){o=document.body}return e.wrap(s),(e[0]===o||t.contains(e[0],o))&&t(o).trigger("focus"),s=e.parent(),"static"===e.css("position")?(s.css({position:"relative"}),e.css({position:"relative"})):(t.extend(i,{position:e.css("position"),zIndex:e.css("z-index")}),t.each(["top","left","bottom","right"],function(t,s){i[s]=e.css(s),isNaN(parseInt(i[s],10))&&(i[s]="auto")}),e.css({position:"relative",top:0,left:0,right:"auto",bottom:"auto"})),e.css(n),s.css(i).show()},removeWrapper:function(e){var i=document.activeElement;return e.parent().is(".ui-effects-wrapper")&&(e.parent().replaceWith(e),(e[0]===i||t.contains(e[0],i))&&t(i).trigger("focus")),e}}),t.extend(t.effects,{version:"1.12.1",define:function(e,i,s){return s||(s=i,i="effect"),t.effects.effect[e]=s,t.effects.effect[e].mode=i,s},scaledDimensions:function(t,e,i){if(0===e)return{height:0,width:0,outerHeight:0,outerWidth:0};var s="horizontal"!==i?(e||100)/100:1,n="vertical"!==i?(e||100)/100:1;return{height:t.height()*n,width:t.width()*s,outerHeight:t.outerHeight()*n,outerWidth:t.outerWidth()*s}},clipToBox:function(t){return{width:t.clip.right-t.clip.left,height:t.clip.bottom-t.clip.top,left:t.clip.left,top:t.clip.top}},unshift:function(t,e,i){var s=t.queue();e>1&&s.splice.apply(s,[1,0].concat(s.splice(e,i))),t.dequeue()},saveStyle:function(t){t.data(u,t[0].style.cssText)},restoreStyle:function(t){t[0].style.cssText=t.data(u)||"",t.removeData(u)},mode:function(t,e){var i=t.is(":hidden");return"toggle"===e&&(e=i?"show":"hide"),(i?"hide"===e:"show"===e)&&(e="none"),e},getBaseline:function(t,e){var i,s;switch(t[0]){case"top":i=0;break;case"middle":i=.5;break;case"bottom":i=1;break;default:i=t[0]/e.height}switch(t[1]){case"left":s=0;break;case"center":s=.5;break;case"right":s=1;break;default:s=t[1]/e.width}return{x:s,y:i}},createPlaceholder:function(e){var i,s=e.css("position"),n=e.position();return e.css({marginTop:e.css("marginTop"),marginBottom:e.css("marginBottom"),marginLeft:e.css("marginLeft"),marginRight:e.css("marginRight")}).outerWidth(e.outerWidth()).outerHeight(e.outerHeight()),/^(static|relative)/.test(s)&&(s="absolute",i=t("<"+e[0].nodeName+">").insertAfter(e).css({display:/^(inline|ruby)/.test(e.css("display"))?"inline-block":"block",visibility:"hidden",marginTop:e.css("marginTop"),marginBottom:e.css("marginBottom"),marginLeft:e.css("marginLeft"),marginRight:e.css("marginRight"),"float":e.css("float")}).outerWidth(e.outerWidth()).outerHeight(e.outerHeight()).addClass("ui-effects-placeholder"),e.data(c+"placeholder",i)),e.css({position:s,left:n.left,top:n.top}),i},removePlaceholder:function(t){var e=c+"placeholder",i=t.data(e);i&&(i.remove(),t.removeData(e))},cleanUp:function(e){t.effects.restoreStyle(e),t.effects.removePlaceholder(e)},setTransition:function(e,i,s,n){return n=n||{},t.each(i,function(t,i){var o=e.cssUnit(i);o[0]>0&&(n[i]=o[0]*s+o[1])}),n}}),t.fn.extend({effect:function(){function i(e){function i(){r.removeData(d),t.effects.cleanUp(r),"hide"===s.mode&&r.hide(),a()}function a(){t.isFunction(h)&&h.call(r[0]),t.isFunction(e)&&e()}var r=t(this);s.mode=c.shift(),t.uiBackCompat===!1||o?"none"===s.mode?(r[l](),a()):n.call(r[0],s,i):(r.is(":hidden")?"hide"===l:"show"===l)?(r[l](),a()):n.call(r[0],s,a)}var s=e.apply(this,arguments),n=t.effects.effect[s.effect],o=n.mode,a=s.queue,r=a||"fx",h=s.complete,l=s.mode,c=[],u=function(e){var i=t(this),s=t.effects.mode(i,l)||o;i.data(d,!0),c.push(s),o&&("show"===s||s===o&&"hide"===s)&&i.show(),o&&"none"===s||t.effects.saveStyle(i),t.isFunction(e)&&e()};return t.fx.off||!n?l?this[l](s.duration,h):this.each(function(){h&&h.call(this)}):a===!1?this.each(u).each(i):this.queue(r,u).queue(r,i)},show:function(t){return function(s){if(i(s))return t.apply(this,arguments);var n=e.apply(this,arguments);return n.mode="show",this.effect.call(this,n)
}}(t.fn.show),hide:function(t){return function(s){if(i(s))return t.apply(this,arguments);var n=e.apply(this,arguments);return n.mode="hide",this.effect.call(this,n)}}(t.fn.hide),toggle:function(t){return function(s){if(i(s)||"boolean"==typeof s)return t.apply(this,arguments);var n=e.apply(this,arguments);return n.mode="toggle",this.effect.call(this,n)}}(t.fn.toggle),cssUnit:function(e){var i=this.css(e),s=[];return t.each(["em","px","%","pt"],function(t,e){i.indexOf(e)>0&&(s=[parseFloat(i),e])}),s},cssClip:function(t){return t?this.css("clip","rect("+t.top+"px "+t.right+"px "+t.bottom+"px "+t.left+"px)"):s(this.css("clip"),this)},transfer:function(e,i){var s=t(this),n=t(e.to),o="fixed"===n.css("position"),a=t("body"),r=o?a.scrollTop():0,h=o?a.scrollLeft():0,l=n.offset(),c={top:l.top-r,left:l.left-h,height:n.innerHeight(),width:n.innerWidth()},u=s.offset(),d=t("<div class='ui-effects-transfer'></div>").appendTo("body").addClass(e.className).css({top:u.top-r,left:u.left-h,height:s.innerHeight(),width:s.innerWidth(),position:o?"fixed":"absolute"}).animate(c,e.duration,e.easing,function(){d.remove(),t.isFunction(i)&&i()})}}),t.fx.step.clip=function(e){e.clipInit||(e.start=t(e.elem).cssClip(),"string"==typeof e.end&&(e.end=s(e.end,e.elem)),e.clipInit=!0),t(e.elem).cssClip({top:e.pos*(e.end.top-e.start.top)+e.start.top,right:e.pos*(e.end.right-e.start.right)+e.start.right,bottom:e.pos*(e.end.bottom-e.start.bottom)+e.start.bottom,left:e.pos*(e.end.left-e.start.left)+e.start.left})}}(),function(){var e={};t.each(["Quad","Cubic","Quart","Quint","Expo"],function(t,i){e[i]=function(e){return Math.pow(e,t+2)}}),t.extend(e,{Sine:function(t){return 1-Math.cos(t*Math.PI/2)},Circ:function(t){return 1-Math.sqrt(1-t*t)},Elastic:function(t){return 0===t||1===t?t:-Math.pow(2,8*(t-1))*Math.sin((80*(t-1)-7.5)*Math.PI/15)},Back:function(t){return t*t*(3*t-2)},Bounce:function(t){for(var e,i=4;((e=Math.pow(2,--i))-1)/11>t;);return 1/Math.pow(4,3-i)-7.5625*Math.pow((3*e-2)/22-t,2)}}),t.each(e,function(e,i){t.easing["easeIn"+e]=i,t.easing["easeOut"+e]=function(t){return 1-i(1-t)},t.easing["easeInOut"+e]=function(t){return.5>t?i(2*t)/2:1-i(-2*t+2)/2}})}();var f=t.effects;t.effects.define("blind","hide",function(e,i){var s={up:["bottom","top"],vertical:["bottom","top"],down:["top","bottom"],left:["right","left"],horizontal:["right","left"],right:["left","right"]},n=t(this),o=e.direction||"up",a=n.cssClip(),r={clip:t.extend({},a)},h=t.effects.createPlaceholder(n);r.clip[s[o][0]]=r.clip[s[o][1]],"show"===e.mode&&(n.cssClip(r.clip),h&&h.css(t.effects.clipToBox(r)),r.clip=a),h&&h.animate(t.effects.clipToBox(r),e.duration,e.easing),n.animate(r,{queue:!1,duration:e.duration,easing:e.easing,complete:i})}),t.effects.define("bounce",function(e,i){var s,n,o,a=t(this),r=e.mode,h="hide"===r,l="show"===r,c=e.direction||"up",u=e.distance,d=e.times||5,p=2*d+(l||h?1:0),f=e.duration/p,g=e.easing,m="up"===c||"down"===c?"top":"left",_="up"===c||"left"===c,v=0,b=a.queue().length;for(t.effects.createPlaceholder(a),o=a.css(m),u||(u=a["top"===m?"outerHeight":"outerWidth"]()/3),l&&(n={opacity:1},n[m]=o,a.css("opacity",0).css(m,_?2*-u:2*u).animate(n,f,g)),h&&(u/=Math.pow(2,d-1)),n={},n[m]=o;d>v;v++)s={},s[m]=(_?"-=":"+=")+u,a.animate(s,f,g).animate(n,f,g),u=h?2*u:u/2;h&&(s={opacity:0},s[m]=(_?"-=":"+=")+u,a.animate(s,f,g)),a.queue(i),t.effects.unshift(a,b,p+1)}),t.effects.define("clip","hide",function(e,i){var s,n={},o=t(this),a=e.direction||"vertical",r="both"===a,h=r||"horizontal"===a,l=r||"vertical"===a;s=o.cssClip(),n.clip={top:l?(s.bottom-s.top)/2:s.top,right:h?(s.right-s.left)/2:s.right,bottom:l?(s.bottom-s.top)/2:s.bottom,left:h?(s.right-s.left)/2:s.left},t.effects.createPlaceholder(o),"show"===e.mode&&(o.cssClip(n.clip),n.clip=s),o.animate(n,{queue:!1,duration:e.duration,easing:e.easing,complete:i})}),t.effects.define("drop","hide",function(e,i){var s,n=t(this),o=e.mode,a="show"===o,r=e.direction||"left",h="up"===r||"down"===r?"top":"left",l="up"===r||"left"===r?"-=":"+=",c="+="===l?"-=":"+=",u={opacity:0};t.effects.createPlaceholder(n),s=e.distance||n["top"===h?"outerHeight":"outerWidth"](!0)/2,u[h]=l+s,a&&(n.css(u),u[h]=c+s,u.opacity=1),n.animate(u,{queue:!1,duration:e.duration,easing:e.easing,complete:i})}),t.effects.define("explode","hide",function(e,i){function s(){b.push(this),b.length===u*d&&n()}function n(){p.css({visibility:"visible"}),t(b).remove(),i()}var o,a,r,h,l,c,u=e.pieces?Math.round(Math.sqrt(e.pieces)):3,d=u,p=t(this),f=e.mode,g="show"===f,m=p.show().css("visibility","hidden").offset(),_=Math.ceil(p.outerWidth()/d),v=Math.ceil(p.outerHeight()/u),b=[];for(o=0;u>o;o++)for(h=m.top+o*v,c=o-(u-1)/2,a=0;d>a;a++)r=m.left+a*_,l=a-(d-1)/2,p.clone().appendTo("body").wrap("<div></div>").css({position:"absolute",visibility:"visible",left:-a*_,top:-o*v}).parent().addClass("ui-effects-explode").css({position:"absolute",overflow:"hidden",width:_,height:v,left:r+(g?l*_:0),top:h+(g?c*v:0),opacity:g?0:1}).animate({left:r+(g?0:l*_),top:h+(g?0:c*v),opacity:g?1:0},e.duration||500,e.easing,s)}),t.effects.define("fade","toggle",function(e,i){var s="show"===e.mode;t(this).css("opacity",s?0:1).animate({opacity:s?1:0},{queue:!1,duration:e.duration,easing:e.easing,complete:i})}),t.effects.define("fold","hide",function(e,i){var s=t(this),n=e.mode,o="show"===n,a="hide"===n,r=e.size||15,h=/([0-9]+)%/.exec(r),l=!!e.horizFirst,c=l?["right","bottom"]:["bottom","right"],u=e.duration/2,d=t.effects.createPlaceholder(s),p=s.cssClip(),f={clip:t.extend({},p)},g={clip:t.extend({},p)},m=[p[c[0]],p[c[1]]],_=s.queue().length;h&&(r=parseInt(h[1],10)/100*m[a?0:1]),f.clip[c[0]]=r,g.clip[c[0]]=r,g.clip[c[1]]=0,o&&(s.cssClip(g.clip),d&&d.css(t.effects.clipToBox(g)),g.clip=p),s.queue(function(i){d&&d.animate(t.effects.clipToBox(f),u,e.easing).animate(t.effects.clipToBox(g),u,e.easing),i()}).animate(f,u,e.easing).animate(g,u,e.easing).queue(i),t.effects.unshift(s,_,4)}),t.effects.define("highlight","show",function(e,i){var s=t(this),n={backgroundColor:s.css("backgroundColor")};"hide"===e.mode&&(n.opacity=0),t.effects.saveStyle(s),s.css({backgroundImage:"none",backgroundColor:e.color||"#ffff99"}).animate(n,{queue:!1,duration:e.duration,easing:e.easing,complete:i})}),t.effects.define("size",function(e,i){var s,n,o,a=t(this),r=["fontSize"],h=["borderTopWidth","borderBottomWidth","paddingTop","paddingBottom"],l=["borderLeftWidth","borderRightWidth","paddingLeft","paddingRight"],c=e.mode,u="effect"!==c,d=e.scale||"both",p=e.origin||["middle","center"],f=a.css("position"),g=a.position(),m=t.effects.scaledDimensions(a),_=e.from||m,v=e.to||t.effects.scaledDimensions(a,0);t.effects.createPlaceholder(a),"show"===c&&(o=_,_=v,v=o),n={from:{y:_.height/m.height,x:_.width/m.width},to:{y:v.height/m.height,x:v.width/m.width}},("box"===d||"both"===d)&&(n.from.y!==n.to.y&&(_=t.effects.setTransition(a,h,n.from.y,_),v=t.effects.setTransition(a,h,n.to.y,v)),n.from.x!==n.to.x&&(_=t.effects.setTransition(a,l,n.from.x,_),v=t.effects.setTransition(a,l,n.to.x,v))),("content"===d||"both"===d)&&n.from.y!==n.to.y&&(_=t.effects.setTransition(a,r,n.from.y,_),v=t.effects.setTransition(a,r,n.to.y,v)),p&&(s=t.effects.getBaseline(p,m),_.top=(m.outerHeight-_.outerHeight)*s.y+g.top,_.left=(m.outerWidth-_.outerWidth)*s.x+g.left,v.top=(m.outerHeight-v.outerHeight)*s.y+g.top,v.left=(m.outerWidth-v.outerWidth)*s.x+g.left),a.css(_),("content"===d||"both"===d)&&(h=h.concat(["marginTop","marginBottom"]).concat(r),l=l.concat(["marginLeft","marginRight"]),a.find("*[width]").each(function(){var i=t(this),s=t.effects.scaledDimensions(i),o={height:s.height*n.from.y,width:s.width*n.from.x,outerHeight:s.outerHeight*n.from.y,outerWidth:s.outerWidth*n.from.x},a={height:s.height*n.to.y,width:s.width*n.to.x,outerHeight:s.height*n.to.y,outerWidth:s.width*n.to.x};n.from.y!==n.to.y&&(o=t.effects.setTransition(i,h,n.from.y,o),a=t.effects.setTransition(i,h,n.to.y,a)),n.from.x!==n.to.x&&(o=t.effects.setTransition(i,l,n.from.x,o),a=t.effects.setTransition(i,l,n.to.x,a)),u&&t.effects.saveStyle(i),i.css(o),i.animate(a,e.duration,e.easing,function(){u&&t.effects.restoreStyle(i)})})),a.animate(v,{queue:!1,duration:e.duration,easing:e.easing,complete:function(){var e=a.offset();0===v.opacity&&a.css("opacity",_.opacity),u||(a.css("position","static"===f?"relative":f).offset(e),t.effects.saveStyle(a)),i()}})}),t.effects.define("scale",function(e,i){var s=t(this),n=e.mode,o=parseInt(e.percent,10)||(0===parseInt(e.percent,10)?0:"effect"!==n?0:100),a=t.extend(!0,{from:t.effects.scaledDimensions(s),to:t.effects.scaledDimensions(s,o,e.direction||"both"),origin:e.origin||["middle","center"]},e);e.fade&&(a.from.opacity=1,a.to.opacity=0),t.effects.effect.size.call(this,a,i)}),t.effects.define("puff","hide",function(e,i){var s=t.extend(!0,{},e,{fade:!0,percent:parseInt(e.percent,10)||150});t.effects.effect.scale.call(this,s,i)}),t.effects.define("pulsate","show",function(e,i){var s=t(this),n=e.mode,o="show"===n,a="hide"===n,r=o||a,h=2*(e.times||5)+(r?1:0),l=e.duration/h,c=0,u=1,d=s.queue().length;for((o||!s.is(":visible"))&&(s.css("opacity",0).show(),c=1);h>u;u++)s.animate({opacity:c},l,e.easing),c=1-c;s.animate({opacity:c},l,e.easing),s.queue(i),t.effects.unshift(s,d,h+1)}),t.effects.define("shake",function(e,i){var s=1,n=t(this),o=e.direction||"left",a=e.distance||20,r=e.times||3,h=2*r+1,l=Math.round(e.duration/h),c="up"===o||"down"===o?"top":"left",u="up"===o||"left"===o,d={},p={},f={},g=n.queue().length;for(t.effects.createPlaceholder(n),d[c]=(u?"-=":"+=")+a,p[c]=(u?"+=":"-=")+2*a,f[c]=(u?"-=":"+=")+2*a,n.animate(d,l,e.easing);r>s;s++)n.animate(p,l,e.easing).animate(f,l,e.easing);n.animate(p,l,e.easing).animate(d,l/2,e.easing).queue(i),t.effects.unshift(n,g,h+1)}),t.effects.define("slide","show",function(e,i){var s,n,o=t(this),a={up:["bottom","top"],down:["top","bottom"],left:["right","left"],right:["left","right"]},r=e.mode,h=e.direction||"left",l="up"===h||"down"===h?"top":"left",c="up"===h||"left"===h,u=e.distance||o["top"===l?"outerHeight":"outerWidth"](!0),d={};t.effects.createPlaceholder(o),s=o.cssClip(),n=o.position()[l],d[l]=(c?-1:1)*u+n,d.clip=o.cssClip(),d.clip[a[h][1]]=d.clip[a[h][0]],"show"===r&&(o.cssClip(d.clip),o.css(l,d[l]),d.clip=s,d[l]=n),o.animate(d,{queue:!1,duration:e.duration,easing:e.easing,complete:i})});var f;t.uiBackCompat!==!1&&(f=t.effects.define("transfer",function(e,i){t(this).transfer(e,i)})),t.ui.focusable=function(i,s){var n,o,a,r,h,l=i.nodeName.toLowerCase();return"area"===l?(n=i.parentNode,o=n.name,i.href&&o&&"map"===n.nodeName.toLowerCase()?(a=t("img[usemap='#"+o+"']"),a.length>0&&a.is(":visible")):!1):(/^(input|select|textarea|button|object)$/.test(l)?(r=!i.disabled,r&&(h=t(i).closest("fieldset")[0],h&&(r=!h.disabled))):r="a"===l?i.href||s:s,r&&t(i).is(":visible")&&e(t(i)))},t.extend(t.expr[":"],{focusable:function(e){return t.ui.focusable(e,null!=t.attr(e,"tabindex"))}}),t.ui.focusable,t.fn.form=function(){return"string"==typeof this[0].form?this.closest("form"):t(this[0].form)},t.ui.formResetMixin={_formResetHandler:function(){var e=t(this);setTimeout(function(){var i=e.data("ui-form-reset-instances");t.each(i,function(){this.refresh()})})},_bindFormResetHandler:function(){if(this.form=this.element.form(),this.form.length){var t=this.form.data("ui-form-reset-instances")||[];t.length||this.form.on("reset.ui-form-reset",this._formResetHandler),t.push(this),this.form.data("ui-form-reset-instances",t)}},_unbindFormResetHandler:function(){if(this.form.length){var e=this.form.data("ui-form-reset-instances");e.splice(t.inArray(this,e),1),e.length?this.form.data("ui-form-reset-instances",e):this.form.removeData("ui-form-reset-instances").off("reset.ui-form-reset")}}},"1.7"===t.fn.jquery.substring(0,3)&&(t.each(["Width","Height"],function(e,i){function s(e,i,s,o){return t.each(n,function(){i-=parseFloat(t.css(e,"padding"+this))||0,s&&(i-=parseFloat(t.css(e,"border"+this+"Width"))||0),o&&(i-=parseFloat(t.css(e,"margin"+this))||0)}),i}var n="Width"===i?["Left","Right"]:["Top","Bottom"],o=i.toLowerCase(),a={innerWidth:t.fn.innerWidth,innerHeight:t.fn.innerHeight,outerWidth:t.fn.outerWidth,outerHeight:t.fn.outerHeight};t.fn["inner"+i]=function(e){return void 0===e?a["inner"+i].call(this):this.each(function(){t(this).css(o,s(this,e)+"px")})},t.fn["outer"+i]=function(e,n){return"number"!=typeof e?a["outer"+i].call(this,e):this.each(function(){t(this).css(o,s(this,e,!0,n)+"px")})}}),t.fn.addBack=function(t){return this.add(null==t?this.prevObject:this.prevObject.filter(t))}),t.ui.keyCode={BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38},t.ui.escapeSelector=function(){var t=/([!"#$%&'()*+,.\/:;<=>?@[\]^`{|}~])/g;return function(e){return e.replace(t,"\\$1")}}(),t.fn.labels=function(){var e,i,s,n,o;return this[0].labels&&this[0].labels.length?this.pushStack(this[0].labels):(n=this.eq(0).parents("label"),s=this.attr("id"),s&&(e=this.eq(0).parents().last(),o=e.add(e.length?e.siblings():this.siblings()),i="label[for='"+t.ui.escapeSelector(s)+"']",n=n.add(o.find(i).addBack(i))),this.pushStack(n))},t.fn.scrollParent=function(e){var i=this.css("position"),s="absolute"===i,n=e?/(auto|scroll|hidden)/:/(auto|scroll)/,o=this.parents().filter(function(){var e=t(this);return s&&"static"===e.css("position")?!1:n.test(e.css("overflow")+e.css("overflow-y")+e.css("overflow-x"))}).eq(0);return"fixed"!==i&&o.length?o:t(this[0].ownerDocument||document)},t.extend(t.expr[":"],{tabbable:function(e){var i=t.attr(e,"tabindex"),s=null!=i;return(!s||i>=0)&&t.ui.focusable(e,s)}}),t.fn.extend({uniqueId:function(){var t=0;return function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++t)})}}(),removeUniqueId:function(){return this.each(function(){/^ui-id-\d+$/.test(this.id)&&t(this).removeAttr("id")})}}),t.widget("ui.accordion",{version:"1.12.1",options:{active:0,animate:{},classes:{"ui-accordion-header":"ui-corner-top","ui-accordion-header-collapsed":"ui-corner-all","ui-accordion-content":"ui-corner-bottom"},collapsible:!1,event:"click",header:"> li > :first-child, > :not(li):even",heightStyle:"auto",icons:{activeHeader:"ui-icon-triangle-1-s",header:"ui-icon-triangle-1-e"},activate:null,beforeActivate:null},hideProps:{borderTopWidth:"hide",borderBottomWidth:"hide",paddingTop:"hide",paddingBottom:"hide",height:"hide"},showProps:{borderTopWidth:"show",borderBottomWidth:"show",paddingTop:"show",paddingBottom:"show",height:"show"},_create:function(){var e=this.options;this.prevShow=this.prevHide=t(),this._addClass("ui-accordion","ui-widget ui-helper-reset"),this.element.attr("role","tablist"),e.collapsible||e.active!==!1&&null!=e.active||(e.active=0),this._processPanels(),0>e.active&&(e.active+=this.headers.length),this._refresh()},_getCreateEventData:function(){return{header:this.active,panel:this.active.length?this.active.next():t()}},_createIcons:function(){var e,i,s=this.options.icons;s&&(e=t("<span>"),this._addClass(e,"ui-accordion-header-icon","ui-icon "+s.header),e.prependTo(this.headers),i=this.active.children(".ui-accordion-header-icon"),this._removeClass(i,s.header)._addClass(i,null,s.activeHeader)._addClass(this.headers,"ui-accordion-icons"))},_destroyIcons:function(){this._removeClass(this.headers,"ui-accordion-icons"),this.headers.children(".ui-accordion-header-icon").remove()},_destroy:function(){var t;this.element.removeAttr("role"),this.headers.removeAttr("role aria-expanded aria-selected aria-controls tabIndex").removeUniqueId(),this._destroyIcons(),t=this.headers.next().css("display","").removeAttr("role aria-hidden aria-labelledby").removeUniqueId(),"content"!==this.options.heightStyle&&t.css("height","")},_setOption:function(t,e){return"active"===t?(this._activate(e),void 0):("event"===t&&(this.options.event&&this._off(this.headers,this.options.event),this._setupEvents(e)),this._super(t,e),"collapsible"!==t||e||this.options.active!==!1||this._activate(0),"icons"===t&&(this._destroyIcons(),e&&this._createIcons()),void 0)},_setOptionDisabled:function(t){this._super(t),this.element.attr("aria-disabled",t),this._toggleClass(null,"ui-state-disabled",!!t),this._toggleClass(this.headers.add(this.headers.next()),null,"ui-state-disabled",!!t)},_keydown:function(e){if(!e.altKey&&!e.ctrlKey){var i=t.ui.keyCode,s=this.headers.length,n=this.headers.index(e.target),o=!1;switch(e.keyCode){case i.RIGHT:case i.DOWN:o=this.headers[(n+1)%s];break;case i.LEFT:case i.UP:o=this.headers[(n-1+s)%s];break;case i.SPACE:case i.ENTER:this._eventHandler(e);break;case i.HOME:o=this.headers[0];break;case i.END:o=this.headers[s-1]}o&&(t(e.target).attr("tabIndex",-1),t(o).attr("tabIndex",0),t(o).trigger("focus"),e.preventDefault())}},_panelKeyDown:function(e){e.keyCode===t.ui.keyCode.UP&&e.ctrlKey&&t(e.currentTarget).prev().trigger("focus")},refresh:function(){var e=this.options;this._processPanels(),e.active===!1&&e.collapsible===!0||!this.headers.length?(e.active=!1,this.active=t()):e.active===!1?this._activate(0):this.active.length&&!t.contains(this.element[0],this.active[0])?this.headers.length===this.headers.find(".ui-state-disabled").length?(e.active=!1,this.active=t()):this._activate(Math.max(0,e.active-1)):e.active=this.headers.index(this.active),this._destroyIcons(),this._refresh()},_processPanels:function(){var t=this.headers,e=this.panels;this.headers=this.element.find(this.options.header),this._addClass(this.headers,"ui-accordion-header ui-accordion-header-collapsed","ui-state-default"),this.panels=this.headers.next().filter(":not(.ui-accordion-content-active)").hide(),this._addClass(this.panels,"ui-accordion-content","ui-helper-reset ui-widget-content"),e&&(this._off(t.not(this.headers)),this._off(e.not(this.panels)))},_refresh:function(){var e,i=this.options,s=i.heightStyle,n=this.element.parent();this.active=this._findActive(i.active),this._addClass(this.active,"ui-accordion-header-active","ui-state-active")._removeClass(this.active,"ui-accordion-header-collapsed"),this._addClass(this.active.next(),"ui-accordion-content-active"),this.active.next().show(),this.headers.attr("role","tab").each(function(){var e=t(this),i=e.uniqueId().attr("id"),s=e.next(),n=s.uniqueId().attr("id");e.attr("aria-controls",n),s.attr("aria-labelledby",i)}).next().attr("role","tabpanel"),this.headers.not(this.active).attr({"aria-selected":"false","aria-expanded":"false",tabIndex:-1}).next().attr({"aria-hidden":"true"}).hide(),this.active.length?this.active.attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0}).next().attr({"aria-hidden":"false"}):this.headers.eq(0).attr("tabIndex",0),this._createIcons(),this._setupEvents(i.event),"fill"===s?(e=n.height(),this.element.siblings(":visible").each(function(){var i=t(this),s=i.css("position");"absolute"!==s&&"fixed"!==s&&(e-=i.outerHeight(!0))}),this.headers.each(function(){e-=t(this).outerHeight(!0)}),this.headers.next().each(function(){t(this).height(Math.max(0,e-t(this).innerHeight()+t(this).height()))}).css("overflow","auto")):"auto"===s&&(e=0,this.headers.next().each(function(){var i=t(this).is(":visible");i||t(this).show(),e=Math.max(e,t(this).css("height","").height()),i||t(this).hide()}).height(e))},_activate:function(e){var i=this._findActive(e)[0];i!==this.active[0]&&(i=i||this.active[0],this._eventHandler({target:i,currentTarget:i,preventDefault:t.noop}))},_findActive:function(e){return"number"==typeof e?this.headers.eq(e):t()},_setupEvents:function(e){var i={keydown:"_keydown"};e&&t.each(e.split(" "),function(t,e){i[e]="_eventHandler"}),this._off(this.headers.add(this.headers.next())),this._on(this.headers,i),this._on(this.headers.next(),{keydown:"_panelKeyDown"}),this._hoverable(this.headers),this._focusable(this.headers)},_eventHandler:function(e){var i,s,n=this.options,o=this.active,a=t(e.currentTarget),r=a[0]===o[0],h=r&&n.collapsible,l=h?t():a.next(),c=o.next(),u={oldHeader:o,oldPanel:c,newHeader:h?t():a,newPanel:l};e.preventDefault(),r&&!n.collapsible||this._trigger("beforeActivate",e,u)===!1||(n.active=h?!1:this.headers.index(a),this.active=r?t():a,this._toggle(u),this._removeClass(o,"ui-accordion-header-active","ui-state-active"),n.icons&&(i=o.children(".ui-accordion-header-icon"),this._removeClass(i,null,n.icons.activeHeader)._addClass(i,null,n.icons.header)),r||(this._removeClass(a,"ui-accordion-header-collapsed")._addClass(a,"ui-accordion-header-active","ui-state-active"),n.icons&&(s=a.children(".ui-accordion-header-icon"),this._removeClass(s,null,n.icons.header)._addClass(s,null,n.icons.activeHeader)),this._addClass(a.next(),"ui-accordion-content-active")))},_toggle:function(e){var i=e.newPanel,s=this.prevShow.length?this.prevShow:e.oldPanel;this.prevShow.add(this.prevHide).stop(!0,!0),this.prevShow=i,this.prevHide=s,this.options.animate?this._animate(i,s,e):(s.hide(),i.show(),this._toggleComplete(e)),s.attr({"aria-hidden":"true"}),s.prev().attr({"aria-selected":"false","aria-expanded":"false"}),i.length&&s.length?s.prev().attr({tabIndex:-1,"aria-expanded":"false"}):i.length&&this.headers.filter(function(){return 0===parseInt(t(this).attr("tabIndex"),10)}).attr("tabIndex",-1),i.attr("aria-hidden","false").prev().attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0})},_animate:function(t,e,i){var s,n,o,a=this,r=0,h=t.css("box-sizing"),l=t.length&&(!e.length||t.index()<e.index()),c=this.options.animate||{},u=l&&c.down||c,d=function(){a._toggleComplete(i)};return"number"==typeof u&&(o=u),"string"==typeof u&&(n=u),n=n||u.easing||c.easing,o=o||u.duration||c.duration,e.length?t.length?(s=t.show().outerHeight(),e.animate(this.hideProps,{duration:o,easing:n,step:function(t,e){e.now=Math.round(t)}}),t.hide().animate(this.showProps,{duration:o,easing:n,complete:d,step:function(t,i){i.now=Math.round(t),"height"!==i.prop?"content-box"===h&&(r+=i.now):"content"!==a.options.heightStyle&&(i.now=Math.round(s-e.outerHeight()-r),r=0)}}),void 0):e.animate(this.hideProps,o,n,d):t.animate(this.showProps,o,n,d)},_toggleComplete:function(t){var e=t.oldPanel,i=e.prev();this._removeClass(e,"ui-accordion-content-active"),this._removeClass(i,"ui-accordion-header-active")._addClass(i,"ui-accordion-header-collapsed"),e.length&&(e.parent()[0].className=e.parent()[0].className),this._trigger("activate",null,t)}}),t.ui.safeActiveElement=function(t){var e;try{e=t.activeElement}catch(i){e=t.body}return e||(e=t.body),e.nodeName||(e=t.body),e},t.widget("ui.menu",{version:"1.12.1",defaultElement:"<ul>",delay:300,options:{icons:{submenu:"ui-icon-caret-1-e"},items:"> *",menus:"ul",position:{my:"left top",at:"right top"},role:"menu",blur:null,focus:null,select:null},_create:function(){this.activeMenu=this.element,this.mouseHandled=!1,this.element.uniqueId().attr({role:this.options.role,tabIndex:0}),this._addClass("ui-menu","ui-widget ui-widget-content"),this._on({"mousedown .ui-menu-item":function(t){t.preventDefault()},"click .ui-menu-item":function(e){var i=t(e.target),s=t(t.ui.safeActiveElement(this.document[0]));!this.mouseHandled&&i.not(".ui-state-disabled").length&&(this.select(e),e.isPropagationStopped()||(this.mouseHandled=!0),i.has(".ui-menu").length?this.expand(e):!this.element.is(":focus")&&s.closest(".ui-menu").length&&(this.element.trigger("focus",[!0]),this.active&&1===this.active.parents(".ui-menu").length&&clearTimeout(this.timer)))},"mouseenter .ui-menu-item":function(e){if(!this.previousFilter){var i=t(e.target).closest(".ui-menu-item"),s=t(e.currentTarget);i[0]===s[0]&&(this._removeClass(s.siblings().children(".ui-state-active"),null,"ui-state-active"),this.focus(e,s))}},mouseleave:"collapseAll","mouseleave .ui-menu":"collapseAll",focus:function(t,e){var i=this.active||this.element.find(this.options.items).eq(0);e||this.focus(t,i)},blur:function(e){this._delay(function(){var i=!t.contains(this.element[0],t.ui.safeActiveElement(this.document[0]));i&&this.collapseAll(e)})},keydown:"_keydown"}),this.refresh(),this._on(this.document,{click:function(t){this._closeOnDocumentClick(t)&&this.collapseAll(t),this.mouseHandled=!1}})},_destroy:function(){var e=this.element.find(".ui-menu-item").removeAttr("role aria-disabled"),i=e.children(".ui-menu-item-wrapper").removeUniqueId().removeAttr("tabIndex role aria-haspopup");this.element.removeAttr("aria-activedescendant").find(".ui-menu").addBack().removeAttr("role aria-labelledby aria-expanded aria-hidden aria-disabled tabIndex").removeUniqueId().show(),i.children().each(function(){var e=t(this);e.data("ui-menu-submenu-caret")&&e.remove()})},_keydown:function(e){var i,s,n,o,a=!0;switch(e.keyCode){case t.ui.keyCode.PAGE_UP:this.previousPage(e);break;case t.ui.keyCode.PAGE_DOWN:this.nextPage(e);break;case t.ui.keyCode.HOME:this._move("first","first",e);break;case t.ui.keyCode.END:this._move("last","last",e);break;case t.ui.keyCode.UP:this.previous(e);break;case t.ui.keyCode.DOWN:this.next(e);break;case t.ui.keyCode.LEFT:this.collapse(e);break;case t.ui.keyCode.RIGHT:this.active&&!this.active.is(".ui-state-disabled")&&this.expand(e);break;case t.ui.keyCode.ENTER:case t.ui.keyCode.SPACE:this._activate(e);break;case t.ui.keyCode.ESCAPE:this.collapse(e);break;default:a=!1,s=this.previousFilter||"",o=!1,n=e.keyCode>=96&&105>=e.keyCode?""+(e.keyCode-96):String.fromCharCode(e.keyCode),clearTimeout(this.filterTimer),n===s?o=!0:n=s+n,i=this._filterMenuItems(n),i=o&&-1!==i.index(this.active.next())?this.active.nextAll(".ui-menu-item"):i,i.length||(n=String.fromCharCode(e.keyCode),i=this._filterMenuItems(n)),i.length?(this.focus(e,i),this.previousFilter=n,this.filterTimer=this._delay(function(){delete this.previousFilter},1e3)):delete this.previousFilter}a&&e.preventDefault()},_activate:function(t){this.active&&!this.active.is(".ui-state-disabled")&&(this.active.children("[aria-haspopup='true']").length?this.expand(t):this.select(t))},refresh:function(){var e,i,s,n,o,a=this,r=this.options.icons.submenu,h=this.element.find(this.options.menus);this._toggleClass("ui-menu-icons",null,!!this.element.find(".ui-icon").length),s=h.filter(":not(.ui-menu)").hide().attr({role:this.options.role,"aria-hidden":"true","aria-expanded":"false"}).each(function(){var e=t(this),i=e.prev(),s=t("<span>").data("ui-menu-submenu-caret",!0);a._addClass(s,"ui-menu-icon","ui-icon "+r),i.attr("aria-haspopup","true").prepend(s),e.attr("aria-labelledby",i.attr("id"))}),this._addClass(s,"ui-menu","ui-widget ui-widget-content ui-front"),e=h.add(this.element),i=e.find(this.options.items),i.not(".ui-menu-item").each(function(){var e=t(this);a._isDivider(e)&&a._addClass(e,"ui-menu-divider","ui-widget-content")}),n=i.not(".ui-menu-item, .ui-menu-divider"),o=n.children().not(".ui-menu").uniqueId().attr({tabIndex:-1,role:this._itemRole()}),this._addClass(n,"ui-menu-item")._addClass(o,"ui-menu-item-wrapper"),i.filter(".ui-state-disabled").attr("aria-disabled","true"),this.active&&!t.contains(this.element[0],this.active[0])&&this.blur()},_itemRole:function(){return{menu:"menuitem",listbox:"option"}[this.options.role]},_setOption:function(t,e){if("icons"===t){var i=this.element.find(".ui-menu-icon");this._removeClass(i,null,this.options.icons.submenu)._addClass(i,null,e.submenu)}this._super(t,e)},_setOptionDisabled:function(t){this._super(t),this.element.attr("aria-disabled",t+""),this._toggleClass(null,"ui-state-disabled",!!t)},focus:function(t,e){var i,s,n;this.blur(t,t&&"focus"===t.type),this._scrollIntoView(e),this.active=e.first(),s=this.active.children(".ui-menu-item-wrapper"),this._addClass(s,null,"ui-state-active"),this.options.role&&this.element.attr("aria-activedescendant",s.attr("id")),n=this.active.parent().closest(".ui-menu-item").children(".ui-menu-item-wrapper"),this._addClass(n,null,"ui-state-active"),t&&"keydown"===t.type?this._close():this.timer=this._delay(function(){this._close()},this.delay),i=e.children(".ui-menu"),i.length&&t&&/^mouse/.test(t.type)&&this._startOpening(i),this.activeMenu=e.parent(),this._trigger("focus",t,{item:e})},_scrollIntoView:function(e){var i,s,n,o,a,r;this._hasScroll()&&(i=parseFloat(t.css(this.activeMenu[0],"borderTopWidth"))||0,s=parseFloat(t.css(this.activeMenu[0],"paddingTop"))||0,n=e.offset().top-this.activeMenu.offset().top-i-s,o=this.activeMenu.scrollTop(),a=this.activeMenu.height(),r=e.outerHeight(),0>n?this.activeMenu.scrollTop(o+n):n+r>a&&this.activeMenu.scrollTop(o+n-a+r))},blur:function(t,e){e||clearTimeout(this.timer),this.active&&(this._removeClass(this.active.children(".ui-menu-item-wrapper"),null,"ui-state-active"),this._trigger("blur",t,{item:this.active}),this.active=null)},_startOpening:function(t){clearTimeout(this.timer),"true"===t.attr("aria-hidden")&&(this.timer=this._delay(function(){this._close(),this._open(t)},this.delay))},_open:function(e){var i=t.extend({of:this.active},this.options.position);clearTimeout(this.timer),this.element.find(".ui-menu").not(e.parents(".ui-menu")).hide().attr("aria-hidden","true"),e.show().removeAttr("aria-hidden").attr("aria-expanded","true").position(i)},collapseAll:function(e,i){clearTimeout(this.timer),this.timer=this._delay(function(){var s=i?this.element:t(e&&e.target).closest(this.element.find(".ui-menu"));s.length||(s=this.element),this._close(s),this.blur(e),this._removeClass(s.find(".ui-state-active"),null,"ui-state-active"),this.activeMenu=s},this.delay)},_close:function(t){t||(t=this.active?this.active.parent():this.element),t.find(".ui-menu").hide().attr("aria-hidden","true").attr("aria-expanded","false")},_closeOnDocumentClick:function(e){return!t(e.target).closest(".ui-menu").length},_isDivider:function(t){return!/[^\-\u2014\u2013\s]/.test(t.text())},collapse:function(t){var e=this.active&&this.active.parent().closest(".ui-menu-item",this.element);e&&e.length&&(this._close(),this.focus(t,e))},expand:function(t){var e=this.active&&this.active.children(".ui-menu ").find(this.options.items).first();e&&e.length&&(this._open(e.parent()),this._delay(function(){this.focus(t,e)}))},next:function(t){this._move("next","first",t)},previous:function(t){this._move("prev","last",t)},isFirstItem:function(){return this.active&&!this.active.prevAll(".ui-menu-item").length},isLastItem:function(){return this.active&&!this.active.nextAll(".ui-menu-item").length},_move:function(t,e,i){var s;this.active&&(s="first"===t||"last"===t?this.active["first"===t?"prevAll":"nextAll"](".ui-menu-item").eq(-1):this.active[t+"All"](".ui-menu-item").eq(0)),s&&s.length&&this.active||(s=this.activeMenu.find(this.options.items)[e]()),this.focus(i,s)},nextPage:function(e){var i,s,n;return this.active?(this.isLastItem()||(this._hasScroll()?(s=this.active.offset().top,n=this.element.height(),this.active.nextAll(".ui-menu-item").each(function(){return i=t(this),0>i.offset().top-s-n}),this.focus(e,i)):this.focus(e,this.activeMenu.find(this.options.items)[this.active?"last":"first"]())),void 0):(this.next(e),void 0)},previousPage:function(e){var i,s,n;return this.active?(this.isFirstItem()||(this._hasScroll()?(s=this.active.offset().top,n=this.element.height(),this.active.prevAll(".ui-menu-item").each(function(){return i=t(this),i.offset().top-s+n>0}),this.focus(e,i)):this.focus(e,this.activeMenu.find(this.options.items).first())),void 0):(this.next(e),void 0)},_hasScroll:function(){return this.element.outerHeight()<this.element.prop("scrollHeight")},select:function(e){this.active=this.active||t(e.target).closest(".ui-menu-item");var i={item:this.active};this.active.has(".ui-menu").length||this.collapseAll(e,!0),this._trigger("select",e,i)},_filterMenuItems:function(e){var i=e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&"),s=RegExp("^"+i,"i");return this.activeMenu.find(this.options.items).filter(".ui-menu-item").filter(function(){return s.test(t.trim(t(this).children(".ui-menu-item-wrapper").text()))})}}),t.widget("ui.autocomplete",{version:"1.12.1",defaultElement:"<input>",options:{appendTo:null,autoFocus:!1,delay:300,minLength:1,position:{my:"left top",at:"left bottom",collision:"none"},source:null,change:null,close:null,focus:null,open:null,response:null,search:null,select:null},requestIndex:0,pending:0,_create:function(){var e,i,s,n=this.element[0].nodeName.toLowerCase(),o="textarea"===n,a="input"===n;
this.isMultiLine=o||!a&&this._isContentEditable(this.element),this.valueMethod=this.element[o||a?"val":"text"],this.isNewMenu=!0,this._addClass("ui-autocomplete-input"),this.element.attr("autocomplete","off"),this._on(this.element,{keydown:function(n){if(this.element.prop("readOnly"))return e=!0,s=!0,i=!0,void 0;e=!1,s=!1,i=!1;var o=t.ui.keyCode;switch(n.keyCode){case o.PAGE_UP:e=!0,this._move("previousPage",n);break;case o.PAGE_DOWN:e=!0,this._move("nextPage",n);break;case o.UP:e=!0,this._keyEvent("previous",n);break;case o.DOWN:e=!0,this._keyEvent("next",n);break;case o.ENTER:this.menu.active&&(e=!0,n.preventDefault(),this.menu.select(n));break;case o.TAB:this.menu.active&&this.menu.select(n);break;case o.ESCAPE:this.menu.element.is(":visible")&&(this.isMultiLine||this._value(this.term),this.close(n),n.preventDefault());break;default:i=!0,this._searchTimeout(n)}},keypress:function(s){if(e)return e=!1,(!this.isMultiLine||this.menu.element.is(":visible"))&&s.preventDefault(),void 0;if(!i){var n=t.ui.keyCode;switch(s.keyCode){case n.PAGE_UP:this._move("previousPage",s);break;case n.PAGE_DOWN:this._move("nextPage",s);break;case n.UP:this._keyEvent("previous",s);break;case n.DOWN:this._keyEvent("next",s)}}},input:function(t){return s?(s=!1,t.preventDefault(),void 0):(this._searchTimeout(t),void 0)},focus:function(){this.selectedItem=null,this.previous=this._value()},blur:function(t){return this.cancelBlur?(delete this.cancelBlur,void 0):(clearTimeout(this.searching),this.close(t),this._change(t),void 0)}}),this._initSource(),this.menu=t("<ul>").appendTo(this._appendTo()).menu({role:null}).hide().menu("instance"),this._addClass(this.menu.element,"ui-autocomplete","ui-front"),this._on(this.menu.element,{mousedown:function(e){e.preventDefault(),this.cancelBlur=!0,this._delay(function(){delete this.cancelBlur,this.element[0]!==t.ui.safeActiveElement(this.document[0])&&this.element.trigger("focus")})},menufocus:function(e,i){var s,n;return this.isNewMenu&&(this.isNewMenu=!1,e.originalEvent&&/^mouse/.test(e.originalEvent.type))?(this.menu.blur(),this.document.one("mousemove",function(){t(e.target).trigger(e.originalEvent)}),void 0):(n=i.item.data("ui-autocomplete-item"),!1!==this._trigger("focus",e,{item:n})&&e.originalEvent&&/^key/.test(e.originalEvent.type)&&this._value(n.value),s=i.item.attr("aria-label")||n.value,s&&t.trim(s).length&&(this.liveRegion.children().hide(),t("<div>").text(s).appendTo(this.liveRegion)),void 0)},menuselect:function(e,i){var s=i.item.data("ui-autocomplete-item"),n=this.previous;this.element[0]!==t.ui.safeActiveElement(this.document[0])&&(this.element.trigger("focus"),this.previous=n,this._delay(function(){this.previous=n,this.selectedItem=s})),!1!==this._trigger("select",e,{item:s})&&this._value(s.value),this.term=this._value(),this.close(e),this.selectedItem=s}}),this.liveRegion=t("<div>",{role:"status","aria-live":"assertive","aria-relevant":"additions"}).appendTo(this.document[0].body),this._addClass(this.liveRegion,null,"ui-helper-hidden-accessible"),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_destroy:function(){clearTimeout(this.searching),this.element.removeAttr("autocomplete"),this.menu.element.remove(),this.liveRegion.remove()},_setOption:function(t,e){this._super(t,e),"source"===t&&this._initSource(),"appendTo"===t&&this.menu.element.appendTo(this._appendTo()),"disabled"===t&&e&&this.xhr&&this.xhr.abort()},_isEventTargetInWidget:function(e){var i=this.menu.element[0];return e.target===this.element[0]||e.target===i||t.contains(i,e.target)},_closeOnClickOutside:function(t){this._isEventTargetInWidget(t)||this.close()},_appendTo:function(){var e=this.options.appendTo;return e&&(e=e.jquery||e.nodeType?t(e):this.document.find(e).eq(0)),e&&e[0]||(e=this.element.closest(".ui-front, dialog")),e.length||(e=this.document[0].body),e},_initSource:function(){var e,i,s=this;t.isArray(this.options.source)?(e=this.options.source,this.source=function(i,s){s(t.ui.autocomplete.filter(e,i.term))}):"string"==typeof this.options.source?(i=this.options.source,this.source=function(e,n){s.xhr&&s.xhr.abort(),s.xhr=t.ajax({url:i,data:e,dataType:"json",success:function(t){n(t)},error:function(){n([])}})}):this.source=this.options.source},_searchTimeout:function(t){clearTimeout(this.searching),this.searching=this._delay(function(){var e=this.term===this._value(),i=this.menu.element.is(":visible"),s=t.altKey||t.ctrlKey||t.metaKey||t.shiftKey;(!e||e&&!i&&!s)&&(this.selectedItem=null,this.search(null,t))},this.options.delay)},search:function(t,e){return t=null!=t?t:this._value(),this.term=this._value(),t.length<this.options.minLength?this.close(e):this._trigger("search",e)!==!1?this._search(t):void 0},_search:function(t){this.pending++,this._addClass("ui-autocomplete-loading"),this.cancelSearch=!1,this.source({term:t},this._response())},_response:function(){var e=++this.requestIndex;return t.proxy(function(t){e===this.requestIndex&&this.__response(t),this.pending--,this.pending||this._removeClass("ui-autocomplete-loading")},this)},__response:function(t){t&&(t=this._normalize(t)),this._trigger("response",null,{content:t}),!this.options.disabled&&t&&t.length&&!this.cancelSearch?(this._suggest(t),this._trigger("open")):this._close()},close:function(t){this.cancelSearch=!0,this._close(t)},_close:function(t){this._off(this.document,"mousedown"),this.menu.element.is(":visible")&&(this.menu.element.hide(),this.menu.blur(),this.isNewMenu=!0,this._trigger("close",t))},_change:function(t){this.previous!==this._value()&&this._trigger("change",t,{item:this.selectedItem})},_normalize:function(e){return e.length&&e[0].label&&e[0].value?e:t.map(e,function(e){return"string"==typeof e?{label:e,value:e}:t.extend({},e,{label:e.label||e.value,value:e.value||e.label})})},_suggest:function(e){var i=this.menu.element.empty();this._renderMenu(i,e),this.isNewMenu=!0,this.menu.refresh(),i.show(),this._resizeMenu(),i.position(t.extend({of:this.element},this.options.position)),this.options.autoFocus&&this.menu.next(),this._on(this.document,{mousedown:"_closeOnClickOutside"})},_resizeMenu:function(){var t=this.menu.element;t.outerWidth(Math.max(t.width("").outerWidth()+1,this.element.outerWidth()))},_renderMenu:function(e,i){var s=this;t.each(i,function(t,i){s._renderItemData(e,i)})},_renderItemData:function(t,e){return this._renderItem(t,e).data("ui-autocomplete-item",e)},_renderItem:function(e,i){return t("<li>").append(t("<div>").text(i.label)).appendTo(e)},_move:function(t,e){return this.menu.element.is(":visible")?this.menu.isFirstItem()&&/^previous/.test(t)||this.menu.isLastItem()&&/^next/.test(t)?(this.isMultiLine||this._value(this.term),this.menu.blur(),void 0):(this.menu[t](e),void 0):(this.search(null,e),void 0)},widget:function(){return this.menu.element},_value:function(){return this.valueMethod.apply(this.element,arguments)},_keyEvent:function(t,e){(!this.isMultiLine||this.menu.element.is(":visible"))&&(this._move(t,e),e.preventDefault())},_isContentEditable:function(t){if(!t.length)return!1;var e=t.prop("contentEditable");return"inherit"===e?this._isContentEditable(t.parent()):"true"===e}}),t.extend(t.ui.autocomplete,{escapeRegex:function(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")},filter:function(e,i){var s=RegExp(t.ui.autocomplete.escapeRegex(i),"i");return t.grep(e,function(t){return s.test(t.label||t.value||t)})}}),t.widget("ui.autocomplete",t.ui.autocomplete,{options:{messages:{noResults:"No search results.",results:function(t){return t+(t>1?" results are":" result is")+" available, use up and down arrow keys to navigate."}}},__response:function(e){var i;this._superApply(arguments),this.options.disabled||this.cancelSearch||(i=e&&e.length?this.options.messages.results(e.length):this.options.messages.noResults,this.liveRegion.children().hide(),t("<div>").text(i).appendTo(this.liveRegion))}}),t.ui.autocomplete;var g=/ui-corner-([a-z]){2,6}/g;t.widget("ui.controlgroup",{version:"1.12.1",defaultElement:"<div>",options:{direction:"horizontal",disabled:null,onlyVisible:!0,items:{button:"input[type=button], input[type=submit], input[type=reset], button, a",controlgroupLabel:".ui-controlgroup-label",checkboxradio:"input[type='checkbox'], input[type='radio']",selectmenu:"select",spinner:".ui-spinner-input"}},_create:function(){this._enhance()},_enhance:function(){this.element.attr("role","toolbar"),this.refresh()},_destroy:function(){this._callChildMethod("destroy"),this.childWidgets.removeData("ui-controlgroup-data"),this.element.removeAttr("role"),this.options.items.controlgroupLabel&&this.element.find(this.options.items.controlgroupLabel).find(".ui-controlgroup-label-contents").contents().unwrap()},_initWidgets:function(){var e=this,i=[];t.each(this.options.items,function(s,n){var o,a={};return n?"controlgroupLabel"===s?(o=e.element.find(n),o.each(function(){var e=t(this);e.children(".ui-controlgroup-label-contents").length||e.contents().wrapAll("<span class='ui-controlgroup-label-contents'></span>")}),e._addClass(o,null,"ui-widget ui-widget-content ui-state-default"),i=i.concat(o.get()),void 0):(t.fn[s]&&(a=e["_"+s+"Options"]?e["_"+s+"Options"]("middle"):{classes:{}},e.element.find(n).each(function(){var n=t(this),o=n[s]("instance"),r=t.widget.extend({},a);if("button"!==s||!n.parent(".ui-spinner").length){o||(o=n[s]()[s]("instance")),o&&(r.classes=e._resolveClassesValues(r.classes,o)),n[s](r);var h=n[s]("widget");t.data(h[0],"ui-controlgroup-data",o?o:n[s]("instance")),i.push(h[0])}})),void 0):void 0}),this.childWidgets=t(t.unique(i)),this._addClass(this.childWidgets,"ui-controlgroup-item")},_callChildMethod:function(e){this.childWidgets.each(function(){var i=t(this),s=i.data("ui-controlgroup-data");s&&s[e]&&s[e]()})},_updateCornerClass:function(t,e){var i="ui-corner-top ui-corner-bottom ui-corner-left ui-corner-right ui-corner-all",s=this._buildSimpleOptions(e,"label").classes.label;this._removeClass(t,null,i),this._addClass(t,null,s)},_buildSimpleOptions:function(t,e){var i="vertical"===this.options.direction,s={classes:{}};return s.classes[e]={middle:"",first:"ui-corner-"+(i?"top":"left"),last:"ui-corner-"+(i?"bottom":"right"),only:"ui-corner-all"}[t],s},_spinnerOptions:function(t){var e=this._buildSimpleOptions(t,"ui-spinner");return e.classes["ui-spinner-up"]="",e.classes["ui-spinner-down"]="",e},_buttonOptions:function(t){return this._buildSimpleOptions(t,"ui-button")},_checkboxradioOptions:function(t){return this._buildSimpleOptions(t,"ui-checkboxradio-label")},_selectmenuOptions:function(t){var e="vertical"===this.options.direction;return{width:e?"auto":!1,classes:{middle:{"ui-selectmenu-button-open":"","ui-selectmenu-button-closed":""},first:{"ui-selectmenu-button-open":"ui-corner-"+(e?"top":"tl"),"ui-selectmenu-button-closed":"ui-corner-"+(e?"top":"left")},last:{"ui-selectmenu-button-open":e?"":"ui-corner-tr","ui-selectmenu-button-closed":"ui-corner-"+(e?"bottom":"right")},only:{"ui-selectmenu-button-open":"ui-corner-top","ui-selectmenu-button-closed":"ui-corner-all"}}[t]}},_resolveClassesValues:function(e,i){var s={};return t.each(e,function(n){var o=i.options.classes[n]||"";o=t.trim(o.replace(g,"")),s[n]=(o+" "+e[n]).replace(/\s+/g," ")}),s},_setOption:function(t,e){return"direction"===t&&this._removeClass("ui-controlgroup-"+this.options.direction),this._super(t,e),"disabled"===t?(this._callChildMethod(e?"disable":"enable"),void 0):(this.refresh(),void 0)},refresh:function(){var e,i=this;this._addClass("ui-controlgroup ui-controlgroup-"+this.options.direction),"horizontal"===this.options.direction&&this._addClass(null,"ui-helper-clearfix"),this._initWidgets(),e=this.childWidgets,this.options.onlyVisible&&(e=e.filter(":visible")),e.length&&(t.each(["first","last"],function(t,s){var n=e[s]().data("ui-controlgroup-data");if(n&&i["_"+n.widgetName+"Options"]){var o=i["_"+n.widgetName+"Options"](1===e.length?"only":s);o.classes=i._resolveClassesValues(o.classes,n),n.element[n.widgetName](o)}else i._updateCornerClass(e[s](),s)}),this._callChildMethod("refresh"))}}),t.widget("ui.checkboxradio",[t.ui.formResetMixin,{version:"1.12.1",options:{disabled:null,label:null,icon:!0,classes:{"ui-checkboxradio-label":"ui-corner-all","ui-checkboxradio-icon":"ui-corner-all"}},_getCreateOptions:function(){var e,i,s=this,n=this._super()||{};return this._readType(),i=this.element.labels(),this.label=t(i[i.length-1]),this.label.length||t.error("No label found for checkboxradio widget"),this.originalLabel="",this.label.contents().not(this.element[0]).each(function(){s.originalLabel+=3===this.nodeType?t(this).text():this.outerHTML}),this.originalLabel&&(n.label=this.originalLabel),e=this.element[0].disabled,null!=e&&(n.disabled=e),n},_create:function(){var t=this.element[0].checked;this._bindFormResetHandler(),null==this.options.disabled&&(this.options.disabled=this.element[0].disabled),this._setOption("disabled",this.options.disabled),this._addClass("ui-checkboxradio","ui-helper-hidden-accessible"),this._addClass(this.label,"ui-checkboxradio-label","ui-button ui-widget"),"radio"===this.type&&this._addClass(this.label,"ui-checkboxradio-radio-label"),this.options.label&&this.options.label!==this.originalLabel?this._updateLabel():this.originalLabel&&(this.options.label=this.originalLabel),this._enhance(),t&&(this._addClass(this.label,"ui-checkboxradio-checked","ui-state-active"),this.icon&&this._addClass(this.icon,null,"ui-state-hover")),this._on({change:"_toggleClasses",focus:function(){this._addClass(this.label,null,"ui-state-focus ui-visual-focus")},blur:function(){this._removeClass(this.label,null,"ui-state-focus ui-visual-focus")}})},_readType:function(){var e=this.element[0].nodeName.toLowerCase();this.type=this.element[0].type,"input"===e&&/radio|checkbox/.test(this.type)||t.error("Can't create checkboxradio on element.nodeName="+e+" and element.type="+this.type)},_enhance:function(){this._updateIcon(this.element[0].checked)},widget:function(){return this.label},_getRadioGroup:function(){var e,i=this.element[0].name,s="input[name='"+t.ui.escapeSelector(i)+"']";return i?(e=this.form.length?t(this.form[0].elements).filter(s):t(s).filter(function(){return 0===t(this).form().length}),e.not(this.element)):t([])},_toggleClasses:function(){var e=this.element[0].checked;this._toggleClass(this.label,"ui-checkboxradio-checked","ui-state-active",e),this.options.icon&&"checkbox"===this.type&&this._toggleClass(this.icon,null,"ui-icon-check ui-state-checked",e)._toggleClass(this.icon,null,"ui-icon-blank",!e),"radio"===this.type&&this._getRadioGroup().each(function(){var e=t(this).checkboxradio("instance");e&&e._removeClass(e.label,"ui-checkboxradio-checked","ui-state-active")})},_destroy:function(){this._unbindFormResetHandler(),this.icon&&(this.icon.remove(),this.iconSpace.remove())},_setOption:function(t,e){return"label"!==t||e?(this._super(t,e),"disabled"===t?(this._toggleClass(this.label,null,"ui-state-disabled",e),this.element[0].disabled=e,void 0):(this.refresh(),void 0)):void 0},_updateIcon:function(e){var i="ui-icon ui-icon-background ";this.options.icon?(this.icon||(this.icon=t("<span>"),this.iconSpace=t("<span> </span>"),this._addClass(this.iconSpace,"ui-checkboxradio-icon-space")),"checkbox"===this.type?(i+=e?"ui-icon-check ui-state-checked":"ui-icon-blank",this._removeClass(this.icon,null,e?"ui-icon-blank":"ui-icon-check")):i+="ui-icon-blank",this._addClass(this.icon,"ui-checkboxradio-icon",i),e||this._removeClass(this.icon,null,"ui-icon-check ui-state-checked"),this.icon.prependTo(this.label).after(this.iconSpace)):void 0!==this.icon&&(this.icon.remove(),this.iconSpace.remove(),delete this.icon)},_updateLabel:function(){var t=this.label.contents().not(this.element[0]);this.icon&&(t=t.not(this.icon[0])),this.iconSpace&&(t=t.not(this.iconSpace[0])),t.remove(),this.label.append(this.options.label)},refresh:function(){var t=this.element[0].checked,e=this.element[0].disabled;this._updateIcon(t),this._toggleClass(this.label,"ui-checkboxradio-checked","ui-state-active",t),null!==this.options.label&&this._updateLabel(),e!==this.options.disabled&&this._setOptions({disabled:e})}}]),t.ui.checkboxradio,t.widget("ui.button",{version:"1.12.1",defaultElement:"<button>",options:{classes:{"ui-button":"ui-corner-all"},disabled:null,icon:null,iconPosition:"beginning",label:null,showLabel:!0},_getCreateOptions:function(){var t,e=this._super()||{};return this.isInput=this.element.is("input"),t=this.element[0].disabled,null!=t&&(e.disabled=t),this.originalLabel=this.isInput?this.element.val():this.element.html(),this.originalLabel&&(e.label=this.originalLabel),e},_create:function(){!this.option.showLabel&!this.options.icon&&(this.options.showLabel=!0),null==this.options.disabled&&(this.options.disabled=this.element[0].disabled||!1),this.hasTitle=!!this.element.attr("title"),this.options.label&&this.options.label!==this.originalLabel&&(this.isInput?this.element.val(this.options.label):this.element.html(this.options.label)),this._addClass("ui-button","ui-widget"),this._setOption("disabled",this.options.disabled),this._enhance(),this.element.is("a")&&this._on({keyup:function(e){e.keyCode===t.ui.keyCode.SPACE&&(e.preventDefault(),this.element[0].click?this.element[0].click():this.element.trigger("click"))}})},_enhance:function(){this.element.is("button")||this.element.attr("role","button"),this.options.icon&&(this._updateIcon("icon",this.options.icon),this._updateTooltip())},_updateTooltip:function(){this.title=this.element.attr("title"),this.options.showLabel||this.title||this.element.attr("title",this.options.label)},_updateIcon:function(e,i){var s="iconPosition"!==e,n=s?this.options.iconPosition:i,o="top"===n||"bottom"===n;this.icon?s&&this._removeClass(this.icon,null,this.options.icon):(this.icon=t("<span>"),this._addClass(this.icon,"ui-button-icon","ui-icon"),this.options.showLabel||this._addClass("ui-button-icon-only")),s&&this._addClass(this.icon,null,i),this._attachIcon(n),o?(this._addClass(this.icon,null,"ui-widget-icon-block"),this.iconSpace&&this.iconSpace.remove()):(this.iconSpace||(this.iconSpace=t("<span> </span>"),this._addClass(this.iconSpace,"ui-button-icon-space")),this._removeClass(this.icon,null,"ui-wiget-icon-block"),this._attachIconSpace(n))},_destroy:function(){this.element.removeAttr("role"),this.icon&&this.icon.remove(),this.iconSpace&&this.iconSpace.remove(),this.hasTitle||this.element.removeAttr("title")},_attachIconSpace:function(t){this.icon[/^(?:end|bottom)/.test(t)?"before":"after"](this.iconSpace)},_attachIcon:function(t){this.element[/^(?:end|bottom)/.test(t)?"append":"prepend"](this.icon)},_setOptions:function(t){var e=void 0===t.showLabel?this.options.showLabel:t.showLabel,i=void 0===t.icon?this.options.icon:t.icon;e||i||(t.showLabel=!0),this._super(t)},_setOption:function(t,e){"icon"===t&&(e?this._updateIcon(t,e):this.icon&&(this.icon.remove(),this.iconSpace&&this.iconSpace.remove())),"iconPosition"===t&&this._updateIcon(t,e),"showLabel"===t&&(this._toggleClass("ui-button-icon-only",null,!e),this._updateTooltip()),"label"===t&&(this.isInput?this.element.val(e):(this.element.html(e),this.icon&&(this._attachIcon(this.options.iconPosition),this._attachIconSpace(this.options.iconPosition)))),this._super(t,e),"disabled"===t&&(this._toggleClass(null,"ui-state-disabled",e),this.element[0].disabled=e,e&&this.element.blur())},refresh:function(){var t=this.element.is("input, button")?this.element[0].disabled:this.element.hasClass("ui-button-disabled");t!==this.options.disabled&&this._setOptions({disabled:t}),this._updateTooltip()}}),t.uiBackCompat!==!1&&(t.widget("ui.button",t.ui.button,{options:{text:!0,icons:{primary:null,secondary:null}},_create:function(){this.options.showLabel&&!this.options.text&&(this.options.showLabel=this.options.text),!this.options.showLabel&&this.options.text&&(this.options.text=this.options.showLabel),this.options.icon||!this.options.icons.primary&&!this.options.icons.secondary?this.options.icon&&(this.options.icons.primary=this.options.icon):this.options.icons.primary?this.options.icon=this.options.icons.primary:(this.options.icon=this.options.icons.secondary,this.options.iconPosition="end"),this._super()},_setOption:function(t,e){return"text"===t?(this._super("showLabel",e),void 0):("showLabel"===t&&(this.options.text=e),"icon"===t&&(this.options.icons.primary=e),"icons"===t&&(e.primary?(this._super("icon",e.primary),this._super("iconPosition","beginning")):e.secondary&&(this._super("icon",e.secondary),this._super("iconPosition","end"))),this._superApply(arguments),void 0)}}),t.fn.button=function(e){return function(){return!this.length||this.length&&"INPUT"!==this[0].tagName||this.length&&"INPUT"===this[0].tagName&&"checkbox"!==this.attr("type")&&"radio"!==this.attr("type")?e.apply(this,arguments):(t.ui.checkboxradio||t.error("Checkboxradio widget missing"),0===arguments.length?this.checkboxradio({icon:!1}):this.checkboxradio.apply(this,arguments))}}(t.fn.button),t.fn.buttonset=function(){return t.ui.controlgroup||t.error("Controlgroup widget missing"),"option"===arguments[0]&&"items"===arguments[1]&&arguments[2]?this.controlgroup.apply(this,[arguments[0],"items.button",arguments[2]]):"option"===arguments[0]&&"items"===arguments[1]?this.controlgroup.apply(this,[arguments[0],"items.button"]):("object"==typeof arguments[0]&&arguments[0].items&&(arguments[0].items={button:arguments[0].items}),this.controlgroup.apply(this,arguments))}),t.ui.button,t.extend(t.ui,{datepicker:{version:"1.12.1"}});var m;t.extend(s.prototype,{markerClassName:"hasDatepicker",maxRows:4,_widgetDatepicker:function(){return this.dpDiv},setDefaults:function(t){return a(this._defaults,t||{}),this},_attachDatepicker:function(e,i){var s,n,o;s=e.nodeName.toLowerCase(),n="div"===s||"span"===s,e.id||(this.uuid+=1,e.id="dp"+this.uuid),o=this._newInst(t(e),n),o.settings=t.extend({},i||{}),"input"===s?this._connectDatepicker(e,o):n&&this._inlineDatepicker(e,o)},_newInst:function(e,i){var s=e[0].id.replace(/([^A-Za-z0-9_\-])/g,"\\\\$1");return{id:s,input:e,selectedDay:0,selectedMonth:0,selectedYear:0,drawMonth:0,drawYear:0,inline:i,dpDiv:i?n(t("<div class='"+this._inlineClass+" ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")):this.dpDiv}},_connectDatepicker:function(e,i){var s=t(e);i.append=t([]),i.trigger=t([]),s.hasClass(this.markerClassName)||(this._attachments(s,i),s.addClass(this.markerClassName).on("keydown",this._doKeyDown).on("keypress",this._doKeyPress).on("keyup",this._doKeyUp),this._autoSize(i),t.data(e,"datepicker",i),i.settings.disabled&&this._disableDatepicker(e))},_attachments:function(e,i){var s,n,o,a=this._get(i,"appendText"),r=this._get(i,"isRTL");i.append&&i.append.remove(),a&&(i.append=t("<span class='"+this._appendClass+"'>"+a+"</span>"),e[r?"before":"after"](i.append)),e.off("focus",this._showDatepicker),i.trigger&&i.trigger.remove(),s=this._get(i,"showOn"),("focus"===s||"both"===s)&&e.on("focus",this._showDatepicker),("button"===s||"both"===s)&&(n=this._get(i,"buttonText"),o=this._get(i,"buttonImage"),i.trigger=t(this._get(i,"buttonImageOnly")?t("<img/>").addClass(this._triggerClass).attr({src:o,alt:n,title:n}):t("<button type='button'></button>").addClass(this._triggerClass).html(o?t("<img/>").attr({src:o,alt:n,title:n}):n)),e[r?"before":"after"](i.trigger),i.trigger.on("click",function(){return t.datepicker._datepickerShowing&&t.datepicker._lastInput===e[0]?t.datepicker._hideDatepicker():t.datepicker._datepickerShowing&&t.datepicker._lastInput!==e[0]?(t.datepicker._hideDatepicker(),t.datepicker._showDatepicker(e[0])):t.datepicker._showDatepicker(e[0]),!1}))},_autoSize:function(t){if(this._get(t,"autoSize")&&!t.inline){var e,i,s,n,o=new Date(2009,11,20),a=this._get(t,"dateFormat");a.match(/[DM]/)&&(e=function(t){for(i=0,s=0,n=0;t.length>n;n++)t[n].length>i&&(i=t[n].length,s=n);return s},o.setMonth(e(this._get(t,a.match(/MM/)?"monthNames":"monthNamesShort"))),o.setDate(e(this._get(t,a.match(/DD/)?"dayNames":"dayNamesShort"))+20-o.getDay())),t.input.attr("size",this._formatDate(t,o).length)}},_inlineDatepicker:function(e,i){var s=t(e);s.hasClass(this.markerClassName)||(s.addClass(this.markerClassName).append(i.dpDiv),t.data(e,"datepicker",i),this._setDate(i,this._getDefaultDate(i),!0),this._updateDatepicker(i),this._updateAlternate(i),i.settings.disabled&&this._disableDatepicker(e),i.dpDiv.css("display","block"))},_dialogDatepicker:function(e,i,s,n,o){var r,h,l,c,u,d=this._dialogInst;return d||(this.uuid+=1,r="dp"+this.uuid,this._dialogInput=t("<input type='text' id='"+r+"' style='position: absolute; top: -100px; width: 0px;'/>"),this._dialogInput.on("keydown",this._doKeyDown),t("body").append(this._dialogInput),d=this._dialogInst=this._newInst(this._dialogInput,!1),d.settings={},t.data(this._dialogInput[0],"datepicker",d)),a(d.settings,n||{}),i=i&&i.constructor===Date?this._formatDate(d,i):i,this._dialogInput.val(i),this._pos=o?o.length?o:[o.pageX,o.pageY]:null,this._pos||(h=document.documentElement.clientWidth,l=document.documentElement.clientHeight,c=document.documentElement.scrollLeft||document.body.scrollLeft,u=document.documentElement.scrollTop||document.body.scrollTop,this._pos=[h/2-100+c,l/2-150+u]),this._dialogInput.css("left",this._pos[0]+20+"px").css("top",this._pos[1]+"px"),d.settings.onSelect=s,this._inDialog=!0,this.dpDiv.addClass(this._dialogClass),this._showDatepicker(this._dialogInput[0]),t.blockUI&&t.blockUI(this.dpDiv),t.data(this._dialogInput[0],"datepicker",d),this},_destroyDatepicker:function(e){var i,s=t(e),n=t.data(e,"datepicker");s.hasClass(this.markerClassName)&&(i=e.nodeName.toLowerCase(),t.removeData(e,"datepicker"),"input"===i?(n.append.remove(),n.trigger.remove(),s.removeClass(this.markerClassName).off("focus",this._showDatepicker).off("keydown",this._doKeyDown).off("keypress",this._doKeyPress).off("keyup",this._doKeyUp)):("div"===i||"span"===i)&&s.removeClass(this.markerClassName).empty(),m===n&&(m=null))},_enableDatepicker:function(e){var i,s,n=t(e),o=t.data(e,"datepicker");n.hasClass(this.markerClassName)&&(i=e.nodeName.toLowerCase(),"input"===i?(e.disabled=!1,o.trigger.filter("button").each(function(){this.disabled=!1}).end().filter("img").css({opacity:"1.0",cursor:""})):("div"===i||"span"===i)&&(s=n.children("."+this._inlineClass),s.children().removeClass("ui-state-disabled"),s.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!1)),this._disabledInputs=t.map(this._disabledInputs,function(t){return t===e?null:t}))},_disableDatepicker:function(e){var i,s,n=t(e),o=t.data(e,"datepicker");n.hasClass(this.markerClassName)&&(i=e.nodeName.toLowerCase(),"input"===i?(e.disabled=!0,o.trigger.filter("button").each(function(){this.disabled=!0}).end().filter("img").css({opacity:"0.5",cursor:"default"})):("div"===i||"span"===i)&&(s=n.children("."+this._inlineClass),s.children().addClass("ui-state-disabled"),s.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!0)),this._disabledInputs=t.map(this._disabledInputs,function(t){return t===e?null:t}),this._disabledInputs[this._disabledInputs.length]=e)},_isDisabledDatepicker:function(t){if(!t)return!1;for(var e=0;this._disabledInputs.length>e;e++)if(this._disabledInputs[e]===t)return!0;return!1},_getInst:function(e){try{return t.data(e,"datepicker")}catch(i){throw"Missing instance data for this datepicker"}},_optionDatepicker:function(e,i,s){var n,o,r,h,l=this._getInst(e);return 2===arguments.length&&"string"==typeof i?"defaults"===i?t.extend({},t.datepicker._defaults):l?"all"===i?t.extend({},l.settings):this._get(l,i):null:(n=i||{},"string"==typeof i&&(n={},n[i]=s),l&&(this._curInst===l&&this._hideDatepicker(),o=this._getDateDatepicker(e,!0),r=this._getMinMaxDate(l,"min"),h=this._getMinMaxDate(l,"max"),a(l.settings,n),null!==r&&void 0!==n.dateFormat&&void 0===n.minDate&&(l.settings.minDate=this._formatDate(l,r)),null!==h&&void 0!==n.dateFormat&&void 0===n.maxDate&&(l.settings.maxDate=this._formatDate(l,h)),"disabled"in n&&(n.disabled?this._disableDatepicker(e):this._enableDatepicker(e)),this._attachments(t(e),l),this._autoSize(l),this._setDate(l,o),this._updateAlternate(l),this._updateDatepicker(l)),void 0)},_changeDatepicker:function(t,e,i){this._optionDatepicker(t,e,i)},_refreshDatepicker:function(t){var e=this._getInst(t);e&&this._updateDatepicker(e)},_setDateDatepicker:function(t,e){var i=this._getInst(t);i&&(this._setDate(i,e),this._updateDatepicker(i),this._updateAlternate(i))},_getDateDatepicker:function(t,e){var i=this._getInst(t);return i&&!i.inline&&this._setDateFromField(i,e),i?this._getDate(i):null},_doKeyDown:function(e){var i,s,n,o=t.datepicker._getInst(e.target),a=!0,r=o.dpDiv.is(".ui-datepicker-rtl");if(o._keyEvent=!0,t.datepicker._datepickerShowing)switch(e.keyCode){case 9:t.datepicker._hideDatepicker(),a=!1;break;case 13:return n=t("td."+t.datepicker._dayOverClass+":not(."+t.datepicker._currentClass+")",o.dpDiv),n[0]&&t.datepicker._selectDay(e.target,o.selectedMonth,o.selectedYear,n[0]),i=t.datepicker._get(o,"onSelect"),i?(s=t.datepicker._formatDate(o),i.apply(o.input?o.input[0]:null,[s,o])):t.datepicker._hideDatepicker(),!1;case 27:t.datepicker._hideDatepicker();break;case 33:t.datepicker._adjustDate(e.target,e.ctrlKey?-t.datepicker._get(o,"stepBigMonths"):-t.datepicker._get(o,"stepMonths"),"M");break;case 34:t.datepicker._adjustDate(e.target,e.ctrlKey?+t.datepicker._get(o,"stepBigMonths"):+t.datepicker._get(o,"stepMonths"),"M");break;case 35:(e.ctrlKey||e.metaKey)&&t.datepicker._clearDate(e.target),a=e.ctrlKey||e.metaKey;break;case 36:(e.ctrlKey||e.metaKey)&&t.datepicker._gotoToday(e.target),a=e.ctrlKey||e.metaKey;break;case 37:(e.ctrlKey||e.metaKey)&&t.datepicker._adjustDate(e.target,r?1:-1,"D"),a=e.ctrlKey||e.metaKey,e.originalEvent.altKey&&t.datepicker._adjustDate(e.target,e.ctrlKey?-t.datepicker._get(o,"stepBigMonths"):-t.datepicker._get(o,"stepMonths"),"M");break;case 38:(e.ctrlKey||e.metaKey)&&t.datepicker._adjustDate(e.target,-7,"D"),a=e.ctrlKey||e.metaKey;break;case 39:(e.ctrlKey||e.metaKey)&&t.datepicker._adjustDate(e.target,r?-1:1,"D"),a=e.ctrlKey||e.metaKey,e.originalEvent.altKey&&t.datepicker._adjustDate(e.target,e.ctrlKey?+t.datepicker._get(o,"stepBigMonths"):+t.datepicker._get(o,"stepMonths"),"M");break;case 40:(e.ctrlKey||e.metaKey)&&t.datepicker._adjustDate(e.target,7,"D"),a=e.ctrlKey||e.metaKey;break;default:a=!1}else 36===e.keyCode&&e.ctrlKey?t.datepicker._showDatepicker(this):a=!1;a&&(e.preventDefault(),e.stopPropagation())},_doKeyPress:function(e){var i,s,n=t.datepicker._getInst(e.target);return t.datepicker._get(n,"constrainInput")?(i=t.datepicker._possibleChars(t.datepicker._get(n,"dateFormat")),s=String.fromCharCode(null==e.charCode?e.keyCode:e.charCode),e.ctrlKey||e.metaKey||" ">s||!i||i.indexOf(s)>-1):void 0},_doKeyUp:function(e){var i,s=t.datepicker._getInst(e.target);if(s.input.val()!==s.lastVal)try{i=t.datepicker.parseDate(t.datepicker._get(s,"dateFormat"),s.input?s.input.val():null,t.datepicker._getFormatConfig(s)),i&&(t.datepicker._setDateFromField(s),t.datepicker._updateAlternate(s),t.datepicker._updateDatepicker(s))}catch(n){}return!0},_showDatepicker:function(e){if(e=e.target||e,"input"!==e.nodeName.toLowerCase()&&(e=t("input",e.parentNode)[0]),!t.datepicker._isDisabledDatepicker(e)&&t.datepicker._lastInput!==e){var s,n,o,r,h,l,c;s=t.datepicker._getInst(e),t.datepicker._curInst&&t.datepicker._curInst!==s&&(t.datepicker._curInst.dpDiv.stop(!0,!0),s&&t.datepicker._datepickerShowing&&t.datepicker._hideDatepicker(t.datepicker._curInst.input[0])),n=t.datepicker._get(s,"beforeShow"),o=n?n.apply(e,[e,s]):{},o!==!1&&(a(s.settings,o),s.lastVal=null,t.datepicker._lastInput=e,t.datepicker._setDateFromField(s),t.datepicker._inDialog&&(e.value=""),t.datepicker._pos||(t.datepicker._pos=t.datepicker._findPos(e),t.datepicker._pos[1]+=e.offsetHeight),r=!1,t(e).parents().each(function(){return r|="fixed"===t(this).css("position"),!r}),h={left:t.datepicker._pos[0],top:t.datepicker._pos[1]},t.datepicker._pos=null,s.dpDiv.empty(),s.dpDiv.css({position:"absolute",display:"block",top:"-1000px"}),t.datepicker._updateDatepicker(s),h=t.datepicker._checkOffset(s,h,r),s.dpDiv.css({position:t.datepicker._inDialog&&t.blockUI?"static":r?"fixed":"absolute",display:"none",left:h.left+"px",top:h.top+"px"}),s.inline||(l=t.datepicker._get(s,"showAnim"),c=t.datepicker._get(s,"duration"),s.dpDiv.css("z-index",i(t(e))+1),t.datepicker._datepickerShowing=!0,t.effects&&t.effects.effect[l]?s.dpDiv.show(l,t.datepicker._get(s,"showOptions"),c):s.dpDiv[l||"show"](l?c:null),t.datepicker._shouldFocusInput(s)&&s.input.trigger("focus"),t.datepicker._curInst=s))
}},_updateDatepicker:function(e){this.maxRows=4,m=e,e.dpDiv.empty().append(this._generateHTML(e)),this._attachHandlers(e);var i,s=this._getNumberOfMonths(e),n=s[1],a=17,r=e.dpDiv.find("."+this._dayOverClass+" a");r.length>0&&o.apply(r.get(0)),e.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width(""),n>1&&e.dpDiv.addClass("ui-datepicker-multi-"+n).css("width",a*n+"em"),e.dpDiv[(1!==s[0]||1!==s[1]?"add":"remove")+"Class"]("ui-datepicker-multi"),e.dpDiv[(this._get(e,"isRTL")?"add":"remove")+"Class"]("ui-datepicker-rtl"),e===t.datepicker._curInst&&t.datepicker._datepickerShowing&&t.datepicker._shouldFocusInput(e)&&e.input.trigger("focus"),e.yearshtml&&(i=e.yearshtml,setTimeout(function(){i===e.yearshtml&&e.yearshtml&&e.dpDiv.find("select.ui-datepicker-year:first").replaceWith(e.yearshtml),i=e.yearshtml=null},0))},_shouldFocusInput:function(t){return t.input&&t.input.is(":visible")&&!t.input.is(":disabled")&&!t.input.is(":focus")},_checkOffset:function(e,i,s){var n=e.dpDiv.outerWidth(),o=e.dpDiv.outerHeight(),a=e.input?e.input.outerWidth():0,r=e.input?e.input.outerHeight():0,h=document.documentElement.clientWidth+(s?0:t(document).scrollLeft()),l=document.documentElement.clientHeight+(s?0:t(document).scrollTop());return i.left-=this._get(e,"isRTL")?n-a:0,i.left-=s&&i.left===e.input.offset().left?t(document).scrollLeft():0,i.top-=s&&i.top===e.input.offset().top+r?t(document).scrollTop():0,i.left-=Math.min(i.left,i.left+n>h&&h>n?Math.abs(i.left+n-h):0),i.top-=Math.min(i.top,i.top+o>l&&l>o?Math.abs(o+r):0),i},_findPos:function(e){for(var i,s=this._getInst(e),n=this._get(s,"isRTL");e&&("hidden"===e.type||1!==e.nodeType||t.expr.filters.hidden(e));)e=e[n?"previousSibling":"nextSibling"];return i=t(e).offset(),[i.left,i.top]},_hideDatepicker:function(e){var i,s,n,o,a=this._curInst;!a||e&&a!==t.data(e,"datepicker")||this._datepickerShowing&&(i=this._get(a,"showAnim"),s=this._get(a,"duration"),n=function(){t.datepicker._tidyDialog(a)},t.effects&&(t.effects.effect[i]||t.effects[i])?a.dpDiv.hide(i,t.datepicker._get(a,"showOptions"),s,n):a.dpDiv["slideDown"===i?"slideUp":"fadeIn"===i?"fadeOut":"hide"](i?s:null,n),i||n(),this._datepickerShowing=!1,o=this._get(a,"onClose"),o&&o.apply(a.input?a.input[0]:null,[a.input?a.input.val():"",a]),this._lastInput=null,this._inDialog&&(this._dialogInput.css({position:"absolute",left:"0",top:"-100px"}),t.blockUI&&(t.unblockUI(),t("body").append(this.dpDiv))),this._inDialog=!1)},_tidyDialog:function(t){t.dpDiv.removeClass(this._dialogClass).off(".ui-datepicker-calendar")},_checkExternalClick:function(e){if(t.datepicker._curInst){var i=t(e.target),s=t.datepicker._getInst(i[0]);(i[0].id!==t.datepicker._mainDivId&&0===i.parents("#"+t.datepicker._mainDivId).length&&!i.hasClass(t.datepicker.markerClassName)&&!i.closest("."+t.datepicker._triggerClass).length&&t.datepicker._datepickerShowing&&(!t.datepicker._inDialog||!t.blockUI)||i.hasClass(t.datepicker.markerClassName)&&t.datepicker._curInst!==s)&&t.datepicker._hideDatepicker()}},_adjustDate:function(e,i,s){var n=t(e),o=this._getInst(n[0]);this._isDisabledDatepicker(n[0])||(this._adjustInstDate(o,i+("M"===s?this._get(o,"showCurrentAtPos"):0),s),this._updateDatepicker(o))},_gotoToday:function(e){var i,s=t(e),n=this._getInst(s[0]);this._get(n,"gotoCurrent")&&n.currentDay?(n.selectedDay=n.currentDay,n.drawMonth=n.selectedMonth=n.currentMonth,n.drawYear=n.selectedYear=n.currentYear):(i=new Date,n.selectedDay=i.getDate(),n.drawMonth=n.selectedMonth=i.getMonth(),n.drawYear=n.selectedYear=i.getFullYear()),this._notifyChange(n),this._adjustDate(s)},_selectMonthYear:function(e,i,s){var n=t(e),o=this._getInst(n[0]);o["selected"+("M"===s?"Month":"Year")]=o["draw"+("M"===s?"Month":"Year")]=parseInt(i.options[i.selectedIndex].value,10),this._notifyChange(o),this._adjustDate(n)},_selectDay:function(e,i,s,n){var o,a=t(e);t(n).hasClass(this._unselectableClass)||this._isDisabledDatepicker(a[0])||(o=this._getInst(a[0]),o.selectedDay=o.currentDay=t("a",n).html(),o.selectedMonth=o.currentMonth=i,o.selectedYear=o.currentYear=s,this._selectDate(e,this._formatDate(o,o.currentDay,o.currentMonth,o.currentYear)))},_clearDate:function(e){var i=t(e);this._selectDate(i,"")},_selectDate:function(e,i){var s,n=t(e),o=this._getInst(n[0]);i=null!=i?i:this._formatDate(o),o.input&&o.input.val(i),this._updateAlternate(o),s=this._get(o,"onSelect"),s?s.apply(o.input?o.input[0]:null,[i,o]):o.input&&o.input.trigger("change"),o.inline?this._updateDatepicker(o):(this._hideDatepicker(),this._lastInput=o.input[0],"object"!=typeof o.input[0]&&o.input.trigger("focus"),this._lastInput=null)},_updateAlternate:function(e){var i,s,n,o=this._get(e,"altField");o&&(i=this._get(e,"altFormat")||this._get(e,"dateFormat"),s=this._getDate(e),n=this.formatDate(i,s,this._getFormatConfig(e)),t(o).val(n))},noWeekends:function(t){var e=t.getDay();return[e>0&&6>e,""]},iso8601Week:function(t){var e,i=new Date(t.getTime());return i.setDate(i.getDate()+4-(i.getDay()||7)),e=i.getTime(),i.setMonth(0),i.setDate(1),Math.floor(Math.round((e-i)/864e5)/7)+1},parseDate:function(e,i,s){if(null==e||null==i)throw"Invalid arguments";if(i="object"==typeof i?""+i:i+"",""===i)return null;var n,o,a,r,h=0,l=(s?s.shortYearCutoff:null)||this._defaults.shortYearCutoff,c="string"!=typeof l?l:(new Date).getFullYear()%100+parseInt(l,10),u=(s?s.dayNamesShort:null)||this._defaults.dayNamesShort,d=(s?s.dayNames:null)||this._defaults.dayNames,p=(s?s.monthNamesShort:null)||this._defaults.monthNamesShort,f=(s?s.monthNames:null)||this._defaults.monthNames,g=-1,m=-1,_=-1,v=-1,b=!1,y=function(t){var i=e.length>n+1&&e.charAt(n+1)===t;return i&&n++,i},w=function(t){var e=y(t),s="@"===t?14:"!"===t?20:"y"===t&&e?4:"o"===t?3:2,n="y"===t?s:1,o=RegExp("^\\d{"+n+","+s+"}"),a=i.substring(h).match(o);if(!a)throw"Missing number at position "+h;return h+=a[0].length,parseInt(a[0],10)},k=function(e,s,n){var o=-1,a=t.map(y(e)?n:s,function(t,e){return[[e,t]]}).sort(function(t,e){return-(t[1].length-e[1].length)});if(t.each(a,function(t,e){var s=e[1];return i.substr(h,s.length).toLowerCase()===s.toLowerCase()?(o=e[0],h+=s.length,!1):void 0}),-1!==o)return o+1;throw"Unknown name at position "+h},x=function(){if(i.charAt(h)!==e.charAt(n))throw"Unexpected literal at position "+h;h++};for(n=0;e.length>n;n++)if(b)"'"!==e.charAt(n)||y("'")?x():b=!1;else switch(e.charAt(n)){case"d":_=w("d");break;case"D":k("D",u,d);break;case"o":v=w("o");break;case"m":m=w("m");break;case"M":m=k("M",p,f);break;case"y":g=w("y");break;case"@":r=new Date(w("@")),g=r.getFullYear(),m=r.getMonth()+1,_=r.getDate();break;case"!":r=new Date((w("!")-this._ticksTo1970)/1e4),g=r.getFullYear(),m=r.getMonth()+1,_=r.getDate();break;case"'":y("'")?x():b=!0;break;default:x()}if(i.length>h&&(a=i.substr(h),!/^\s+/.test(a)))throw"Extra/unparsed characters found in date: "+a;if(-1===g?g=(new Date).getFullYear():100>g&&(g+=(new Date).getFullYear()-(new Date).getFullYear()%100+(c>=g?0:-100)),v>-1)for(m=1,_=v;;){if(o=this._getDaysInMonth(g,m-1),o>=_)break;m++,_-=o}if(r=this._daylightSavingAdjust(new Date(g,m-1,_)),r.getFullYear()!==g||r.getMonth()+1!==m||r.getDate()!==_)throw"Invalid date";return r},ATOM:"yy-mm-dd",COOKIE:"D, dd M yy",ISO_8601:"yy-mm-dd",RFC_822:"D, d M y",RFC_850:"DD, dd-M-y",RFC_1036:"D, d M y",RFC_1123:"D, d M yy",RFC_2822:"D, d M yy",RSS:"D, d M y",TICKS:"!",TIMESTAMP:"@",W3C:"yy-mm-dd",_ticksTo1970:1e7*60*60*24*(718685+Math.floor(492.5)-Math.floor(19.7)+Math.floor(4.925)),formatDate:function(t,e,i){if(!e)return"";var s,n=(i?i.dayNamesShort:null)||this._defaults.dayNamesShort,o=(i?i.dayNames:null)||this._defaults.dayNames,a=(i?i.monthNamesShort:null)||this._defaults.monthNamesShort,r=(i?i.monthNames:null)||this._defaults.monthNames,h=function(e){var i=t.length>s+1&&t.charAt(s+1)===e;return i&&s++,i},l=function(t,e,i){var s=""+e;if(h(t))for(;i>s.length;)s="0"+s;return s},c=function(t,e,i,s){return h(t)?s[e]:i[e]},u="",d=!1;if(e)for(s=0;t.length>s;s++)if(d)"'"!==t.charAt(s)||h("'")?u+=t.charAt(s):d=!1;else switch(t.charAt(s)){case"d":u+=l("d",e.getDate(),2);break;case"D":u+=c("D",e.getDay(),n,o);break;case"o":u+=l("o",Math.round((new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime()-new Date(e.getFullYear(),0,0).getTime())/864e5),3);break;case"m":u+=l("m",e.getMonth()+1,2);break;case"M":u+=c("M",e.getMonth(),a,r);break;case"y":u+=h("y")?e.getFullYear():(10>e.getFullYear()%100?"0":"")+e.getFullYear()%100;break;case"@":u+=e.getTime();break;case"!":u+=1e4*e.getTime()+this._ticksTo1970;break;case"'":h("'")?u+="'":d=!0;break;default:u+=t.charAt(s)}return u},_possibleChars:function(t){var e,i="",s=!1,n=function(i){var s=t.length>e+1&&t.charAt(e+1)===i;return s&&e++,s};for(e=0;t.length>e;e++)if(s)"'"!==t.charAt(e)||n("'")?i+=t.charAt(e):s=!1;else switch(t.charAt(e)){case"d":case"m":case"y":case"@":i+="0123456789";break;case"D":case"M":return null;case"'":n("'")?i+="'":s=!0;break;default:i+=t.charAt(e)}return i},_get:function(t,e){return void 0!==t.settings[e]?t.settings[e]:this._defaults[e]},_setDateFromField:function(t,e){if(t.input.val()!==t.lastVal){var i=this._get(t,"dateFormat"),s=t.lastVal=t.input?t.input.val():null,n=this._getDefaultDate(t),o=n,a=this._getFormatConfig(t);try{o=this.parseDate(i,s,a)||n}catch(r){s=e?"":s}t.selectedDay=o.getDate(),t.drawMonth=t.selectedMonth=o.getMonth(),t.drawYear=t.selectedYear=o.getFullYear(),t.currentDay=s?o.getDate():0,t.currentMonth=s?o.getMonth():0,t.currentYear=s?o.getFullYear():0,this._adjustInstDate(t)}},_getDefaultDate:function(t){return this._restrictMinMax(t,this._determineDate(t,this._get(t,"defaultDate"),new Date))},_determineDate:function(e,i,s){var n=function(t){var e=new Date;return e.setDate(e.getDate()+t),e},o=function(i){try{return t.datepicker.parseDate(t.datepicker._get(e,"dateFormat"),i,t.datepicker._getFormatConfig(e))}catch(s){}for(var n=(i.toLowerCase().match(/^c/)?t.datepicker._getDate(e):null)||new Date,o=n.getFullYear(),a=n.getMonth(),r=n.getDate(),h=/([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,l=h.exec(i);l;){switch(l[2]||"d"){case"d":case"D":r+=parseInt(l[1],10);break;case"w":case"W":r+=7*parseInt(l[1],10);break;case"m":case"M":a+=parseInt(l[1],10),r=Math.min(r,t.datepicker._getDaysInMonth(o,a));break;case"y":case"Y":o+=parseInt(l[1],10),r=Math.min(r,t.datepicker._getDaysInMonth(o,a))}l=h.exec(i)}return new Date(o,a,r)},a=null==i||""===i?s:"string"==typeof i?o(i):"number"==typeof i?isNaN(i)?s:n(i):new Date(i.getTime());return a=a&&"Invalid Date"==""+a?s:a,a&&(a.setHours(0),a.setMinutes(0),a.setSeconds(0),a.setMilliseconds(0)),this._daylightSavingAdjust(a)},_daylightSavingAdjust:function(t){return t?(t.setHours(t.getHours()>12?t.getHours()+2:0),t):null},_setDate:function(t,e,i){var s=!e,n=t.selectedMonth,o=t.selectedYear,a=this._restrictMinMax(t,this._determineDate(t,e,new Date));t.selectedDay=t.currentDay=a.getDate(),t.drawMonth=t.selectedMonth=t.currentMonth=a.getMonth(),t.drawYear=t.selectedYear=t.currentYear=a.getFullYear(),n===t.selectedMonth&&o===t.selectedYear||i||this._notifyChange(t),this._adjustInstDate(t),t.input&&t.input.val(s?"":this._formatDate(t))},_getDate:function(t){var e=!t.currentYear||t.input&&""===t.input.val()?null:this._daylightSavingAdjust(new Date(t.currentYear,t.currentMonth,t.currentDay));return e},_attachHandlers:function(e){var i=this._get(e,"stepMonths"),s="#"+e.id.replace(/\\\\/g,"\\");e.dpDiv.find("[data-handler]").map(function(){var e={prev:function(){t.datepicker._adjustDate(s,-i,"M")},next:function(){t.datepicker._adjustDate(s,+i,"M")},hide:function(){t.datepicker._hideDatepicker()},today:function(){t.datepicker._gotoToday(s)},selectDay:function(){return t.datepicker._selectDay(s,+this.getAttribute("data-month"),+this.getAttribute("data-year"),this),!1},selectMonth:function(){return t.datepicker._selectMonthYear(s,this,"M"),!1},selectYear:function(){return t.datepicker._selectMonthYear(s,this,"Y"),!1}};t(this).on(this.getAttribute("data-event"),e[this.getAttribute("data-handler")])})},_generateHTML:function(t){var e,i,s,n,o,a,r,h,l,c,u,d,p,f,g,m,_,v,b,y,w,k,x,C,D,I,T,P,M,S,H,z,O,A,N,W,E,F,L,R=new Date,B=this._daylightSavingAdjust(new Date(R.getFullYear(),R.getMonth(),R.getDate())),Y=this._get(t,"isRTL"),j=this._get(t,"showButtonPanel"),q=this._get(t,"hideIfNoPrevNext"),K=this._get(t,"navigationAsDateFormat"),U=this._getNumberOfMonths(t),V=this._get(t,"showCurrentAtPos"),$=this._get(t,"stepMonths"),X=1!==U[0]||1!==U[1],G=this._daylightSavingAdjust(t.currentDay?new Date(t.currentYear,t.currentMonth,t.currentDay):new Date(9999,9,9)),Q=this._getMinMaxDate(t,"min"),J=this._getMinMaxDate(t,"max"),Z=t.drawMonth-V,te=t.drawYear;if(0>Z&&(Z+=12,te--),J)for(e=this._daylightSavingAdjust(new Date(J.getFullYear(),J.getMonth()-U[0]*U[1]+1,J.getDate())),e=Q&&Q>e?Q:e;this._daylightSavingAdjust(new Date(te,Z,1))>e;)Z--,0>Z&&(Z=11,te--);for(t.drawMonth=Z,t.drawYear=te,i=this._get(t,"prevText"),i=K?this.formatDate(i,this._daylightSavingAdjust(new Date(te,Z-$,1)),this._getFormatConfig(t)):i,s=this._canAdjustMonth(t,-1,te,Z)?"<a class='ui-datepicker-prev ui-corner-all' data-handler='prev' data-event='click' title='"+i+"'><span class='ui-icon ui-icon-circle-triangle-"+(Y?"e":"w")+"'>"+i+"</span></a>":q?"":"<a class='ui-datepicker-prev ui-corner-all ui-state-disabled' title='"+i+"'><span class='ui-icon ui-icon-circle-triangle-"+(Y?"e":"w")+"'>"+i+"</span></a>",n=this._get(t,"nextText"),n=K?this.formatDate(n,this._daylightSavingAdjust(new Date(te,Z+$,1)),this._getFormatConfig(t)):n,o=this._canAdjustMonth(t,1,te,Z)?"<a class='ui-datepicker-next ui-corner-all' data-handler='next' data-event='click' title='"+n+"'><span class='ui-icon ui-icon-circle-triangle-"+(Y?"w":"e")+"'>"+n+"</span></a>":q?"":"<a class='ui-datepicker-next ui-corner-all ui-state-disabled' title='"+n+"'><span class='ui-icon ui-icon-circle-triangle-"+(Y?"w":"e")+"'>"+n+"</span></a>",a=this._get(t,"currentText"),r=this._get(t,"gotoCurrent")&&t.currentDay?G:B,a=K?this.formatDate(a,r,this._getFormatConfig(t)):a,h=t.inline?"":"<button type='button' class='ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all' data-handler='hide' data-event='click'>"+this._get(t,"closeText")+"</button>",l=j?"<div class='ui-datepicker-buttonpane ui-widget-content'>"+(Y?h:"")+(this._isInRange(t,r)?"<button type='button' class='ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all' data-handler='today' data-event='click'>"+a+"</button>":"")+(Y?"":h)+"</div>":"",c=parseInt(this._get(t,"firstDay"),10),c=isNaN(c)?0:c,u=this._get(t,"showWeek"),d=this._get(t,"dayNames"),p=this._get(t,"dayNamesMin"),f=this._get(t,"monthNames"),g=this._get(t,"monthNamesShort"),m=this._get(t,"beforeShowDay"),_=this._get(t,"showOtherMonths"),v=this._get(t,"selectOtherMonths"),b=this._getDefaultDate(t),y="",k=0;U[0]>k;k++){for(x="",this.maxRows=4,C=0;U[1]>C;C++){if(D=this._daylightSavingAdjust(new Date(te,Z,t.selectedDay)),I=" ui-corner-all",T="",X){if(T+="<div class='ui-datepicker-group",U[1]>1)switch(C){case 0:T+=" ui-datepicker-group-first",I=" ui-corner-"+(Y?"right":"left");break;case U[1]-1:T+=" ui-datepicker-group-last",I=" ui-corner-"+(Y?"left":"right");break;default:T+=" ui-datepicker-group-middle",I=""}T+="'>"}for(T+="<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix"+I+"'>"+(/all|left/.test(I)&&0===k?Y?o:s:"")+(/all|right/.test(I)&&0===k?Y?s:o:"")+this._generateMonthYearHeader(t,Z,te,Q,J,k>0||C>0,f,g)+"</div><table class='ui-datepicker-calendar'><thead>"+"<tr>",P=u?"<th class='ui-datepicker-week-col'>"+this._get(t,"weekHeader")+"</th>":"",w=0;7>w;w++)M=(w+c)%7,P+="<th scope='col'"+((w+c+6)%7>=5?" class='ui-datepicker-week-end'":"")+">"+"<span title='"+d[M]+"'>"+p[M]+"</span></th>";for(T+=P+"</tr></thead><tbody>",S=this._getDaysInMonth(te,Z),te===t.selectedYear&&Z===t.selectedMonth&&(t.selectedDay=Math.min(t.selectedDay,S)),H=(this._getFirstDayOfMonth(te,Z)-c+7)%7,z=Math.ceil((H+S)/7),O=X?this.maxRows>z?this.maxRows:z:z,this.maxRows=O,A=this._daylightSavingAdjust(new Date(te,Z,1-H)),N=0;O>N;N++){for(T+="<tr>",W=u?"<td class='ui-datepicker-week-col'>"+this._get(t,"calculateWeek")(A)+"</td>":"",w=0;7>w;w++)E=m?m.apply(t.input?t.input[0]:null,[A]):[!0,""],F=A.getMonth()!==Z,L=F&&!v||!E[0]||Q&&Q>A||J&&A>J,W+="<td class='"+((w+c+6)%7>=5?" ui-datepicker-week-end":"")+(F?" ui-datepicker-other-month":"")+(A.getTime()===D.getTime()&&Z===t.selectedMonth&&t._keyEvent||b.getTime()===A.getTime()&&b.getTime()===D.getTime()?" "+this._dayOverClass:"")+(L?" "+this._unselectableClass+" ui-state-disabled":"")+(F&&!_?"":" "+E[1]+(A.getTime()===G.getTime()?" "+this._currentClass:"")+(A.getTime()===B.getTime()?" ui-datepicker-today":""))+"'"+(F&&!_||!E[2]?"":" title='"+E[2].replace(/'/g,"&#39;")+"'")+(L?"":" data-handler='selectDay' data-event='click' data-month='"+A.getMonth()+"' data-year='"+A.getFullYear()+"'")+">"+(F&&!_?"&#xa0;":L?"<span class='ui-state-default'>"+A.getDate()+"</span>":"<a class='ui-state-default"+(A.getTime()===B.getTime()?" ui-state-highlight":"")+(A.getTime()===G.getTime()?" ui-state-active":"")+(F?" ui-priority-secondary":"")+"' href='#'>"+A.getDate()+"</a>")+"</td>",A.setDate(A.getDate()+1),A=this._daylightSavingAdjust(A);T+=W+"</tr>"}Z++,Z>11&&(Z=0,te++),T+="</tbody></table>"+(X?"</div>"+(U[0]>0&&C===U[1]-1?"<div class='ui-datepicker-row-break'></div>":""):""),x+=T}y+=x}return y+=l,t._keyEvent=!1,y},_generateMonthYearHeader:function(t,e,i,s,n,o,a,r){var h,l,c,u,d,p,f,g,m=this._get(t,"changeMonth"),_=this._get(t,"changeYear"),v=this._get(t,"showMonthAfterYear"),b="<div class='ui-datepicker-title'>",y="";if(o||!m)y+="<span class='ui-datepicker-month'>"+a[e]+"</span>";else{for(h=s&&s.getFullYear()===i,l=n&&n.getFullYear()===i,y+="<select class='ui-datepicker-month' data-handler='selectMonth' data-event='change'>",c=0;12>c;c++)(!h||c>=s.getMonth())&&(!l||n.getMonth()>=c)&&(y+="<option value='"+c+"'"+(c===e?" selected='selected'":"")+">"+r[c]+"</option>");y+="</select>"}if(v||(b+=y+(!o&&m&&_?"":"&#xa0;")),!t.yearshtml)if(t.yearshtml="",o||!_)b+="<span class='ui-datepicker-year'>"+i+"</span>";else{for(u=this._get(t,"yearRange").split(":"),d=(new Date).getFullYear(),p=function(t){var e=t.match(/c[+\-].*/)?i+parseInt(t.substring(1),10):t.match(/[+\-].*/)?d+parseInt(t,10):parseInt(t,10);return isNaN(e)?d:e},f=p(u[0]),g=Math.max(f,p(u[1]||"")),f=s?Math.max(f,s.getFullYear()):f,g=n?Math.min(g,n.getFullYear()):g,t.yearshtml+="<select class='ui-datepicker-year' data-handler='selectYear' data-event='change'>";g>=f;f++)t.yearshtml+="<option value='"+f+"'"+(f===i?" selected='selected'":"")+">"+f+"</option>";t.yearshtml+="</select>",b+=t.yearshtml,t.yearshtml=null}return b+=this._get(t,"yearSuffix"),v&&(b+=(!o&&m&&_?"":"&#xa0;")+y),b+="</div>"},_adjustInstDate:function(t,e,i){var s=t.selectedYear+("Y"===i?e:0),n=t.selectedMonth+("M"===i?e:0),o=Math.min(t.selectedDay,this._getDaysInMonth(s,n))+("D"===i?e:0),a=this._restrictMinMax(t,this._daylightSavingAdjust(new Date(s,n,o)));t.selectedDay=a.getDate(),t.drawMonth=t.selectedMonth=a.getMonth(),t.drawYear=t.selectedYear=a.getFullYear(),("M"===i||"Y"===i)&&this._notifyChange(t)},_restrictMinMax:function(t,e){var i=this._getMinMaxDate(t,"min"),s=this._getMinMaxDate(t,"max"),n=i&&i>e?i:e;return s&&n>s?s:n},_notifyChange:function(t){var e=this._get(t,"onChangeMonthYear");e&&e.apply(t.input?t.input[0]:null,[t.selectedYear,t.selectedMonth+1,t])},_getNumberOfMonths:function(t){var e=this._get(t,"numberOfMonths");return null==e?[1,1]:"number"==typeof e?[1,e]:e},_getMinMaxDate:function(t,e){return this._determineDate(t,this._get(t,e+"Date"),null)},_getDaysInMonth:function(t,e){return 32-this._daylightSavingAdjust(new Date(t,e,32)).getDate()},_getFirstDayOfMonth:function(t,e){return new Date(t,e,1).getDay()},_canAdjustMonth:function(t,e,i,s){var n=this._getNumberOfMonths(t),o=this._daylightSavingAdjust(new Date(i,s+(0>e?e:n[0]*n[1]),1));return 0>e&&o.setDate(this._getDaysInMonth(o.getFullYear(),o.getMonth())),this._isInRange(t,o)},_isInRange:function(t,e){var i,s,n=this._getMinMaxDate(t,"min"),o=this._getMinMaxDate(t,"max"),a=null,r=null,h=this._get(t,"yearRange");return h&&(i=h.split(":"),s=(new Date).getFullYear(),a=parseInt(i[0],10),r=parseInt(i[1],10),i[0].match(/[+\-].*/)&&(a+=s),i[1].match(/[+\-].*/)&&(r+=s)),(!n||e.getTime()>=n.getTime())&&(!o||e.getTime()<=o.getTime())&&(!a||e.getFullYear()>=a)&&(!r||r>=e.getFullYear())},_getFormatConfig:function(t){var e=this._get(t,"shortYearCutoff");return e="string"!=typeof e?e:(new Date).getFullYear()%100+parseInt(e,10),{shortYearCutoff:e,dayNamesShort:this._get(t,"dayNamesShort"),dayNames:this._get(t,"dayNames"),monthNamesShort:this._get(t,"monthNamesShort"),monthNames:this._get(t,"monthNames")}},_formatDate:function(t,e,i,s){e||(t.currentDay=t.selectedDay,t.currentMonth=t.selectedMonth,t.currentYear=t.selectedYear);var n=e?"object"==typeof e?e:this._daylightSavingAdjust(new Date(s,i,e)):this._daylightSavingAdjust(new Date(t.currentYear,t.currentMonth,t.currentDay));return this.formatDate(this._get(t,"dateFormat"),n,this._getFormatConfig(t))}}),t.fn.datepicker=function(e){if(!this.length)return this;t.datepicker.initialized||(t(document).on("mousedown",t.datepicker._checkExternalClick),t.datepicker.initialized=!0),0===t("#"+t.datepicker._mainDivId).length&&t("body").append(t.datepicker.dpDiv);var i=Array.prototype.slice.call(arguments,1);return"string"!=typeof e||"isDisabled"!==e&&"getDate"!==e&&"widget"!==e?"option"===e&&2===arguments.length&&"string"==typeof arguments[1]?t.datepicker["_"+e+"Datepicker"].apply(t.datepicker,[this[0]].concat(i)):this.each(function(){"string"==typeof e?t.datepicker["_"+e+"Datepicker"].apply(t.datepicker,[this].concat(i)):t.datepicker._attachDatepicker(this,e)}):t.datepicker["_"+e+"Datepicker"].apply(t.datepicker,[this[0]].concat(i))},t.datepicker=new s,t.datepicker.initialized=!1,t.datepicker.uuid=(new Date).getTime(),t.datepicker.version="1.12.1",t.datepicker,t.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase());var _=!1;t(document).on("mouseup",function(){_=!1}),t.widget("ui.mouse",{version:"1.12.1",options:{cancel:"input, textarea, button, select, option",distance:1,delay:0},_mouseInit:function(){var e=this;this.element.on("mousedown."+this.widgetName,function(t){return e._mouseDown(t)}).on("click."+this.widgetName,function(i){return!0===t.data(i.target,e.widgetName+".preventClickEvent")?(t.removeData(i.target,e.widgetName+".preventClickEvent"),i.stopImmediatePropagation(),!1):void 0}),this.started=!1},_mouseDestroy:function(){this.element.off("."+this.widgetName),this._mouseMoveDelegate&&this.document.off("mousemove."+this.widgetName,this._mouseMoveDelegate).off("mouseup."+this.widgetName,this._mouseUpDelegate)},_mouseDown:function(e){if(!_){this._mouseMoved=!1,this._mouseStarted&&this._mouseUp(e),this._mouseDownEvent=e;var i=this,s=1===e.which,n="string"==typeof this.options.cancel&&e.target.nodeName?t(e.target).closest(this.options.cancel).length:!1;return s&&!n&&this._mouseCapture(e)?(this.mouseDelayMet=!this.options.delay,this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){i.mouseDelayMet=!0},this.options.delay)),this._mouseDistanceMet(e)&&this._mouseDelayMet(e)&&(this._mouseStarted=this._mouseStart(e)!==!1,!this._mouseStarted)?(e.preventDefault(),!0):(!0===t.data(e.target,this.widgetName+".preventClickEvent")&&t.removeData(e.target,this.widgetName+".preventClickEvent"),this._mouseMoveDelegate=function(t){return i._mouseMove(t)},this._mouseUpDelegate=function(t){return i._mouseUp(t)},this.document.on("mousemove."+this.widgetName,this._mouseMoveDelegate).on("mouseup."+this.widgetName,this._mouseUpDelegate),e.preventDefault(),_=!0,!0)):!0}},_mouseMove:function(e){if(this._mouseMoved){if(t.ui.ie&&(!document.documentMode||9>document.documentMode)&&!e.button)return this._mouseUp(e);if(!e.which)if(e.originalEvent.altKey||e.originalEvent.ctrlKey||e.originalEvent.metaKey||e.originalEvent.shiftKey)this.ignoreMissingWhich=!0;else if(!this.ignoreMissingWhich)return this._mouseUp(e)}return(e.which||e.button)&&(this._mouseMoved=!0),this._mouseStarted?(this._mouseDrag(e),e.preventDefault()):(this._mouseDistanceMet(e)&&this._mouseDelayMet(e)&&(this._mouseStarted=this._mouseStart(this._mouseDownEvent,e)!==!1,this._mouseStarted?this._mouseDrag(e):this._mouseUp(e)),!this._mouseStarted)},_mouseUp:function(e){this.document.off("mousemove."+this.widgetName,this._mouseMoveDelegate).off("mouseup."+this.widgetName,this._mouseUpDelegate),this._mouseStarted&&(this._mouseStarted=!1,e.target===this._mouseDownEvent.target&&t.data(e.target,this.widgetName+".preventClickEvent",!0),this._mouseStop(e)),this._mouseDelayTimer&&(clearTimeout(this._mouseDelayTimer),delete this._mouseDelayTimer),this.ignoreMissingWhich=!1,_=!1,e.preventDefault()},_mouseDistanceMet:function(t){return Math.max(Math.abs(this._mouseDownEvent.pageX-t.pageX),Math.abs(this._mouseDownEvent.pageY-t.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return!0}}),t.ui.plugin={add:function(e,i,s){var n,o=t.ui[e].prototype;for(n in s)o.plugins[n]=o.plugins[n]||[],o.plugins[n].push([i,s[n]])},call:function(t,e,i,s){var n,o=t.plugins[e];if(o&&(s||t.element[0].parentNode&&11!==t.element[0].parentNode.nodeType))for(n=0;o.length>n;n++)t.options[o[n][0]]&&o[n][1].apply(t.element,i)}},t.ui.safeBlur=function(e){e&&"body"!==e.nodeName.toLowerCase()&&t(e).trigger("blur")},t.widget("ui.draggable",t.ui.mouse,{version:"1.12.1",widgetEventPrefix:"drag",options:{addClasses:!0,appendTo:"parent",axis:!1,connectToSortable:!1,containment:!1,cursor:"auto",cursorAt:!1,grid:!1,handle:!1,helper:"original",iframeFix:!1,opacity:!1,refreshPositions:!1,revert:!1,revertDuration:500,scope:"default",scroll:!0,scrollSensitivity:20,scrollSpeed:20,snap:!1,snapMode:"both",snapTolerance:20,stack:!1,zIndex:!1,drag:null,start:null,stop:null},_create:function(){"original"===this.options.helper&&this._setPositionRelative(),this.options.addClasses&&this._addClass("ui-draggable"),this._setHandleClassName(),this._mouseInit()},_setOption:function(t,e){this._super(t,e),"handle"===t&&(this._removeHandleClassName(),this._setHandleClassName())},_destroy:function(){return(this.helper||this.element).is(".ui-draggable-dragging")?(this.destroyOnClear=!0,void 0):(this._removeHandleClassName(),this._mouseDestroy(),void 0)},_mouseCapture:function(e){var i=this.options;return this.helper||i.disabled||t(e.target).closest(".ui-resizable-handle").length>0?!1:(this.handle=this._getHandle(e),this.handle?(this._blurActiveElement(e),this._blockFrames(i.iframeFix===!0?"iframe":i.iframeFix),!0):!1)},_blockFrames:function(e){this.iframeBlocks=this.document.find(e).map(function(){var e=t(this);return t("<div>").css("position","absolute").appendTo(e.parent()).outerWidth(e.outerWidth()).outerHeight(e.outerHeight()).offset(e.offset())[0]})},_unblockFrames:function(){this.iframeBlocks&&(this.iframeBlocks.remove(),delete this.iframeBlocks)},_blurActiveElement:function(e){var i=t.ui.safeActiveElement(this.document[0]),s=t(e.target);s.closest(i).length||t.ui.safeBlur(i)},_mouseStart:function(e){var i=this.options;return this.helper=this._createHelper(e),this._addClass(this.helper,"ui-draggable-dragging"),this._cacheHelperProportions(),t.ui.ddmanager&&(t.ui.ddmanager.current=this),this._cacheMargins(),this.cssPosition=this.helper.css("position"),this.scrollParent=this.helper.scrollParent(!0),this.offsetParent=this.helper.offsetParent(),this.hasFixedAncestor=this.helper.parents().filter(function(){return"fixed"===t(this).css("position")}).length>0,this.positionAbs=this.element.offset(),this._refreshOffsets(e),this.originalPosition=this.position=this._generatePosition(e,!1),this.originalPageX=e.pageX,this.originalPageY=e.pageY,i.cursorAt&&this._adjustOffsetFromHelper(i.cursorAt),this._setContainment(),this._trigger("start",e)===!1?(this._clear(),!1):(this._cacheHelperProportions(),t.ui.ddmanager&&!i.dropBehaviour&&t.ui.ddmanager.prepareOffsets(this,e),this._mouseDrag(e,!0),t.ui.ddmanager&&t.ui.ddmanager.dragStart(this,e),!0)},_refreshOffsets:function(t){this.offset={top:this.positionAbs.top-this.margins.top,left:this.positionAbs.left-this.margins.left,scroll:!1,parent:this._getParentOffset(),relative:this._getRelativeOffset()},this.offset.click={left:t.pageX-this.offset.left,top:t.pageY-this.offset.top}},_mouseDrag:function(e,i){if(this.hasFixedAncestor&&(this.offset.parent=this._getParentOffset()),this.position=this._generatePosition(e,!0),this.positionAbs=this._convertPositionTo("absolute"),!i){var s=this._uiHash();if(this._trigger("drag",e,s)===!1)return this._mouseUp(new t.Event("mouseup",e)),!1;this.position=s.position}return this.helper[0].style.left=this.position.left+"px",this.helper[0].style.top=this.position.top+"px",t.ui.ddmanager&&t.ui.ddmanager.drag(this,e),!1},_mouseStop:function(e){var i=this,s=!1;return t.ui.ddmanager&&!this.options.dropBehaviour&&(s=t.ui.ddmanager.drop(this,e)),this.dropped&&(s=this.dropped,this.dropped=!1),"invalid"===this.options.revert&&!s||"valid"===this.options.revert&&s||this.options.revert===!0||t.isFunction(this.options.revert)&&this.options.revert.call(this.element,s)?t(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){i._trigger("stop",e)!==!1&&i._clear()}):this._trigger("stop",e)!==!1&&this._clear(),!1},_mouseUp:function(e){return this._unblockFrames(),t.ui.ddmanager&&t.ui.ddmanager.dragStop(this,e),this.handleElement.is(e.target)&&this.element.trigger("focus"),t.ui.mouse.prototype._mouseUp.call(this,e)},cancel:function(){return this.helper.is(".ui-draggable-dragging")?this._mouseUp(new t.Event("mouseup",{target:this.element[0]})):this._clear(),this},_getHandle:function(e){return this.options.handle?!!t(e.target).closest(this.element.find(this.options.handle)).length:!0},_setHandleClassName:function(){this.handleElement=this.options.handle?this.element.find(this.options.handle):this.element,this._addClass(this.handleElement,"ui-draggable-handle")},_removeHandleClassName:function(){this._removeClass(this.handleElement,"ui-draggable-handle")},_createHelper:function(e){var i=this.options,s=t.isFunction(i.helper),n=s?t(i.helper.apply(this.element[0],[e])):"clone"===i.helper?this.element.clone().removeAttr("id"):this.element;return n.parents("body").length||n.appendTo("parent"===i.appendTo?this.element[0].parentNode:i.appendTo),s&&n[0]===this.element[0]&&this._setPositionRelative(),n[0]===this.element[0]||/(fixed|absolute)/.test(n.css("position"))||n.css("position","absolute"),n},_setPositionRelative:function(){/^(?:r|a|f)/.test(this.element.css("position"))||(this.element[0].style.position="relative")},_adjustOffsetFromHelper:function(e){"string"==typeof e&&(e=e.split(" ")),t.isArray(e)&&(e={left:+e[0],top:+e[1]||0}),"left"in e&&(this.offset.click.left=e.left+this.margins.left),"right"in e&&(this.offset.click.left=this.helperProportions.width-e.right+this.margins.left),"top"in e&&(this.offset.click.top=e.top+this.margins.top),"bottom"in e&&(this.offset.click.top=this.helperProportions.height-e.bottom+this.margins.top)},_isRootNode:function(t){return/(html|body)/i.test(t.tagName)||t===this.document[0]},_getParentOffset:function(){var e=this.offsetParent.offset(),i=this.document[0];return"absolute"===this.cssPosition&&this.scrollParent[0]!==i&&t.contains(this.scrollParent[0],this.offsetParent[0])&&(e.left+=this.scrollParent.scrollLeft(),e.top+=this.scrollParent.scrollTop()),this._isRootNode(this.offsetParent[0])&&(e={top:0,left:0}),{top:e.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:e.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"!==this.cssPosition)return{top:0,left:0};var t=this.element.position(),e=this._isRootNode(this.scrollParent[0]);return{top:t.top-(parseInt(this.helper.css("top"),10)||0)+(e?0:this.scrollParent.scrollTop()),left:t.left-(parseInt(this.helper.css("left"),10)||0)+(e?0:this.scrollParent.scrollLeft())}
},_cacheMargins:function(){this.margins={left:parseInt(this.element.css("marginLeft"),10)||0,top:parseInt(this.element.css("marginTop"),10)||0,right:parseInt(this.element.css("marginRight"),10)||0,bottom:parseInt(this.element.css("marginBottom"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var e,i,s,n=this.options,o=this.document[0];return this.relativeContainer=null,n.containment?"window"===n.containment?(this.containment=[t(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,t(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,t(window).scrollLeft()+t(window).width()-this.helperProportions.width-this.margins.left,t(window).scrollTop()+(t(window).height()||o.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top],void 0):"document"===n.containment?(this.containment=[0,0,t(o).width()-this.helperProportions.width-this.margins.left,(t(o).height()||o.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top],void 0):n.containment.constructor===Array?(this.containment=n.containment,void 0):("parent"===n.containment&&(n.containment=this.helper[0].parentNode),i=t(n.containment),s=i[0],s&&(e=/(scroll|auto)/.test(i.css("overflow")),this.containment=[(parseInt(i.css("borderLeftWidth"),10)||0)+(parseInt(i.css("paddingLeft"),10)||0),(parseInt(i.css("borderTopWidth"),10)||0)+(parseInt(i.css("paddingTop"),10)||0),(e?Math.max(s.scrollWidth,s.offsetWidth):s.offsetWidth)-(parseInt(i.css("borderRightWidth"),10)||0)-(parseInt(i.css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(e?Math.max(s.scrollHeight,s.offsetHeight):s.offsetHeight)-(parseInt(i.css("borderBottomWidth"),10)||0)-(parseInt(i.css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom],this.relativeContainer=i),void 0):(this.containment=null,void 0)},_convertPositionTo:function(t,e){e||(e=this.position);var i="absolute"===t?1:-1,s=this._isRootNode(this.scrollParent[0]);return{top:e.top+this.offset.relative.top*i+this.offset.parent.top*i-("fixed"===this.cssPosition?-this.offset.scroll.top:s?0:this.offset.scroll.top)*i,left:e.left+this.offset.relative.left*i+this.offset.parent.left*i-("fixed"===this.cssPosition?-this.offset.scroll.left:s?0:this.offset.scroll.left)*i}},_generatePosition:function(t,e){var i,s,n,o,a=this.options,r=this._isRootNode(this.scrollParent[0]),h=t.pageX,l=t.pageY;return r&&this.offset.scroll||(this.offset.scroll={top:this.scrollParent.scrollTop(),left:this.scrollParent.scrollLeft()}),e&&(this.containment&&(this.relativeContainer?(s=this.relativeContainer.offset(),i=[this.containment[0]+s.left,this.containment[1]+s.top,this.containment[2]+s.left,this.containment[3]+s.top]):i=this.containment,t.pageX-this.offset.click.left<i[0]&&(h=i[0]+this.offset.click.left),t.pageY-this.offset.click.top<i[1]&&(l=i[1]+this.offset.click.top),t.pageX-this.offset.click.left>i[2]&&(h=i[2]+this.offset.click.left),t.pageY-this.offset.click.top>i[3]&&(l=i[3]+this.offset.click.top)),a.grid&&(n=a.grid[1]?this.originalPageY+Math.round((l-this.originalPageY)/a.grid[1])*a.grid[1]:this.originalPageY,l=i?n-this.offset.click.top>=i[1]||n-this.offset.click.top>i[3]?n:n-this.offset.click.top>=i[1]?n-a.grid[1]:n+a.grid[1]:n,o=a.grid[0]?this.originalPageX+Math.round((h-this.originalPageX)/a.grid[0])*a.grid[0]:this.originalPageX,h=i?o-this.offset.click.left>=i[0]||o-this.offset.click.left>i[2]?o:o-this.offset.click.left>=i[0]?o-a.grid[0]:o+a.grid[0]:o),"y"===a.axis&&(h=this.originalPageX),"x"===a.axis&&(l=this.originalPageY)),{top:l-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.offset.scroll.top:r?0:this.offset.scroll.top),left:h-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.offset.scroll.left:r?0:this.offset.scroll.left)}},_clear:function(){this._removeClass(this.helper,"ui-draggable-dragging"),this.helper[0]===this.element[0]||this.cancelHelperRemoval||this.helper.remove(),this.helper=null,this.cancelHelperRemoval=!1,this.destroyOnClear&&this.destroy()},_trigger:function(e,i,s){return s=s||this._uiHash(),t.ui.plugin.call(this,e,[i,s,this],!0),/^(drag|start|stop)/.test(e)&&(this.positionAbs=this._convertPositionTo("absolute"),s.offset=this.positionAbs),t.Widget.prototype._trigger.call(this,e,i,s)},plugins:{},_uiHash:function(){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}}),t.ui.plugin.add("draggable","connectToSortable",{start:function(e,i,s){var n=t.extend({},i,{item:s.element});s.sortables=[],t(s.options.connectToSortable).each(function(){var i=t(this).sortable("instance");i&&!i.options.disabled&&(s.sortables.push(i),i.refreshPositions(),i._trigger("activate",e,n))})},stop:function(e,i,s){var n=t.extend({},i,{item:s.element});s.cancelHelperRemoval=!1,t.each(s.sortables,function(){var t=this;t.isOver?(t.isOver=0,s.cancelHelperRemoval=!0,t.cancelHelperRemoval=!1,t._storedCSS={position:t.placeholder.css("position"),top:t.placeholder.css("top"),left:t.placeholder.css("left")},t._mouseStop(e),t.options.helper=t.options._helper):(t.cancelHelperRemoval=!0,t._trigger("deactivate",e,n))})},drag:function(e,i,s){t.each(s.sortables,function(){var n=!1,o=this;o.positionAbs=s.positionAbs,o.helperProportions=s.helperProportions,o.offset.click=s.offset.click,o._intersectsWith(o.containerCache)&&(n=!0,t.each(s.sortables,function(){return this.positionAbs=s.positionAbs,this.helperProportions=s.helperProportions,this.offset.click=s.offset.click,this!==o&&this._intersectsWith(this.containerCache)&&t.contains(o.element[0],this.element[0])&&(n=!1),n})),n?(o.isOver||(o.isOver=1,s._parent=i.helper.parent(),o.currentItem=i.helper.appendTo(o.element).data("ui-sortable-item",!0),o.options._helper=o.options.helper,o.options.helper=function(){return i.helper[0]},e.target=o.currentItem[0],o._mouseCapture(e,!0),o._mouseStart(e,!0,!0),o.offset.click.top=s.offset.click.top,o.offset.click.left=s.offset.click.left,o.offset.parent.left-=s.offset.parent.left-o.offset.parent.left,o.offset.parent.top-=s.offset.parent.top-o.offset.parent.top,s._trigger("toSortable",e),s.dropped=o.element,t.each(s.sortables,function(){this.refreshPositions()}),s.currentItem=s.element,o.fromOutside=s),o.currentItem&&(o._mouseDrag(e),i.position=o.position)):o.isOver&&(o.isOver=0,o.cancelHelperRemoval=!0,o.options._revert=o.options.revert,o.options.revert=!1,o._trigger("out",e,o._uiHash(o)),o._mouseStop(e,!0),o.options.revert=o.options._revert,o.options.helper=o.options._helper,o.placeholder&&o.placeholder.remove(),i.helper.appendTo(s._parent),s._refreshOffsets(e),i.position=s._generatePosition(e,!0),s._trigger("fromSortable",e),s.dropped=!1,t.each(s.sortables,function(){this.refreshPositions()}))})}}),t.ui.plugin.add("draggable","cursor",{start:function(e,i,s){var n=t("body"),o=s.options;n.css("cursor")&&(o._cursor=n.css("cursor")),n.css("cursor",o.cursor)},stop:function(e,i,s){var n=s.options;n._cursor&&t("body").css("cursor",n._cursor)}}),t.ui.plugin.add("draggable","opacity",{start:function(e,i,s){var n=t(i.helper),o=s.options;n.css("opacity")&&(o._opacity=n.css("opacity")),n.css("opacity",o.opacity)},stop:function(e,i,s){var n=s.options;n._opacity&&t(i.helper).css("opacity",n._opacity)}}),t.ui.plugin.add("draggable","scroll",{start:function(t,e,i){i.scrollParentNotHidden||(i.scrollParentNotHidden=i.helper.scrollParent(!1)),i.scrollParentNotHidden[0]!==i.document[0]&&"HTML"!==i.scrollParentNotHidden[0].tagName&&(i.overflowOffset=i.scrollParentNotHidden.offset())},drag:function(e,i,s){var n=s.options,o=!1,a=s.scrollParentNotHidden[0],r=s.document[0];a!==r&&"HTML"!==a.tagName?(n.axis&&"x"===n.axis||(s.overflowOffset.top+a.offsetHeight-e.pageY<n.scrollSensitivity?a.scrollTop=o=a.scrollTop+n.scrollSpeed:e.pageY-s.overflowOffset.top<n.scrollSensitivity&&(a.scrollTop=o=a.scrollTop-n.scrollSpeed)),n.axis&&"y"===n.axis||(s.overflowOffset.left+a.offsetWidth-e.pageX<n.scrollSensitivity?a.scrollLeft=o=a.scrollLeft+n.scrollSpeed:e.pageX-s.overflowOffset.left<n.scrollSensitivity&&(a.scrollLeft=o=a.scrollLeft-n.scrollSpeed))):(n.axis&&"x"===n.axis||(e.pageY-t(r).scrollTop()<n.scrollSensitivity?o=t(r).scrollTop(t(r).scrollTop()-n.scrollSpeed):t(window).height()-(e.pageY-t(r).scrollTop())<n.scrollSensitivity&&(o=t(r).scrollTop(t(r).scrollTop()+n.scrollSpeed))),n.axis&&"y"===n.axis||(e.pageX-t(r).scrollLeft()<n.scrollSensitivity?o=t(r).scrollLeft(t(r).scrollLeft()-n.scrollSpeed):t(window).width()-(e.pageX-t(r).scrollLeft())<n.scrollSensitivity&&(o=t(r).scrollLeft(t(r).scrollLeft()+n.scrollSpeed)))),o!==!1&&t.ui.ddmanager&&!n.dropBehaviour&&t.ui.ddmanager.prepareOffsets(s,e)}}),t.ui.plugin.add("draggable","snap",{start:function(e,i,s){var n=s.options;s.snapElements=[],t(n.snap.constructor!==String?n.snap.items||":data(ui-draggable)":n.snap).each(function(){var e=t(this),i=e.offset();this!==s.element[0]&&s.snapElements.push({item:this,width:e.outerWidth(),height:e.outerHeight(),top:i.top,left:i.left})})},drag:function(e,i,s){var n,o,a,r,h,l,c,u,d,p,f=s.options,g=f.snapTolerance,m=i.offset.left,_=m+s.helperProportions.width,v=i.offset.top,b=v+s.helperProportions.height;for(d=s.snapElements.length-1;d>=0;d--)h=s.snapElements[d].left-s.margins.left,l=h+s.snapElements[d].width,c=s.snapElements[d].top-s.margins.top,u=c+s.snapElements[d].height,h-g>_||m>l+g||c-g>b||v>u+g||!t.contains(s.snapElements[d].item.ownerDocument,s.snapElements[d].item)?(s.snapElements[d].snapping&&s.options.snap.release&&s.options.snap.release.call(s.element,e,t.extend(s._uiHash(),{snapItem:s.snapElements[d].item})),s.snapElements[d].snapping=!1):("inner"!==f.snapMode&&(n=g>=Math.abs(c-b),o=g>=Math.abs(u-v),a=g>=Math.abs(h-_),r=g>=Math.abs(l-m),n&&(i.position.top=s._convertPositionTo("relative",{top:c-s.helperProportions.height,left:0}).top),o&&(i.position.top=s._convertPositionTo("relative",{top:u,left:0}).top),a&&(i.position.left=s._convertPositionTo("relative",{top:0,left:h-s.helperProportions.width}).left),r&&(i.position.left=s._convertPositionTo("relative",{top:0,left:l}).left)),p=n||o||a||r,"outer"!==f.snapMode&&(n=g>=Math.abs(c-v),o=g>=Math.abs(u-b),a=g>=Math.abs(h-m),r=g>=Math.abs(l-_),n&&(i.position.top=s._convertPositionTo("relative",{top:c,left:0}).top),o&&(i.position.top=s._convertPositionTo("relative",{top:u-s.helperProportions.height,left:0}).top),a&&(i.position.left=s._convertPositionTo("relative",{top:0,left:h}).left),r&&(i.position.left=s._convertPositionTo("relative",{top:0,left:l-s.helperProportions.width}).left)),!s.snapElements[d].snapping&&(n||o||a||r||p)&&s.options.snap.snap&&s.options.snap.snap.call(s.element,e,t.extend(s._uiHash(),{snapItem:s.snapElements[d].item})),s.snapElements[d].snapping=n||o||a||r||p)}}),t.ui.plugin.add("draggable","stack",{start:function(e,i,s){var n,o=s.options,a=t.makeArray(t(o.stack)).sort(function(e,i){return(parseInt(t(e).css("zIndex"),10)||0)-(parseInt(t(i).css("zIndex"),10)||0)});a.length&&(n=parseInt(t(a[0]).css("zIndex"),10)||0,t(a).each(function(e){t(this).css("zIndex",n+e)}),this.css("zIndex",n+a.length))}}),t.ui.plugin.add("draggable","zIndex",{start:function(e,i,s){var n=t(i.helper),o=s.options;n.css("zIndex")&&(o._zIndex=n.css("zIndex")),n.css("zIndex",o.zIndex)},stop:function(e,i,s){var n=s.options;n._zIndex&&t(i.helper).css("zIndex",n._zIndex)}}),t.ui.draggable,t.widget("ui.resizable",t.ui.mouse,{version:"1.12.1",widgetEventPrefix:"resize",options:{alsoResize:!1,animate:!1,animateDuration:"slow",animateEasing:"swing",aspectRatio:!1,autoHide:!1,classes:{"ui-resizable-se":"ui-icon ui-icon-gripsmall-diagonal-se"},containment:!1,ghost:!1,grid:!1,handles:"e,s,se",helper:!1,maxHeight:null,maxWidth:null,minHeight:10,minWidth:10,zIndex:90,resize:null,start:null,stop:null},_num:function(t){return parseFloat(t)||0},_isNumber:function(t){return!isNaN(parseFloat(t))},_hasScroll:function(e,i){if("hidden"===t(e).css("overflow"))return!1;var s=i&&"left"===i?"scrollLeft":"scrollTop",n=!1;return e[s]>0?!0:(e[s]=1,n=e[s]>0,e[s]=0,n)},_create:function(){var e,i=this.options,s=this;this._addClass("ui-resizable"),t.extend(this,{_aspectRatio:!!i.aspectRatio,aspectRatio:i.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:i.helper||i.ghost||i.animate?i.helper||"ui-resizable-helper":null}),this.element[0].nodeName.match(/^(canvas|textarea|input|select|button|img)$/i)&&(this.element.wrap(t("<div class='ui-wrapper' style='overflow: hidden;'></div>").css({position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.outerHeight(),top:this.element.css("top"),left:this.element.css("left")})),this.element=this.element.parent().data("ui-resizable",this.element.resizable("instance")),this.elementIsWrapper=!0,e={marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom"),marginLeft:this.originalElement.css("marginLeft")},this.element.css(e),this.originalElement.css("margin",0),this.originalResizeStyle=this.originalElement.css("resize"),this.originalElement.css("resize","none"),this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"})),this.originalElement.css(e),this._proportionallyResize()),this._setupHandles(),i.autoHide&&t(this.element).on("mouseenter",function(){i.disabled||(s._removeClass("ui-resizable-autohide"),s._handles.show())}).on("mouseleave",function(){i.disabled||s.resizing||(s._addClass("ui-resizable-autohide"),s._handles.hide())}),this._mouseInit()},_destroy:function(){this._mouseDestroy();var e,i=function(e){t(e).removeData("resizable").removeData("ui-resizable").off(".resizable").find(".ui-resizable-handle").remove()};return this.elementIsWrapper&&(i(this.element),e=this.element,this.originalElement.css({position:e.css("position"),width:e.outerWidth(),height:e.outerHeight(),top:e.css("top"),left:e.css("left")}).insertAfter(e),e.remove()),this.originalElement.css("resize",this.originalResizeStyle),i(this.originalElement),this},_setOption:function(t,e){switch(this._super(t,e),t){case"handles":this._removeHandles(),this._setupHandles();break;default:}},_setupHandles:function(){var e,i,s,n,o,a=this.options,r=this;if(this.handles=a.handles||(t(".ui-resizable-handle",this.element).length?{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw",ne:".ui-resizable-ne",nw:".ui-resizable-nw"}:"e,s,se"),this._handles=t(),this.handles.constructor===String)for("all"===this.handles&&(this.handles="n,e,s,w,se,sw,ne,nw"),s=this.handles.split(","),this.handles={},i=0;s.length>i;i++)e=t.trim(s[i]),n="ui-resizable-"+e,o=t("<div>"),this._addClass(o,"ui-resizable-handle "+n),o.css({zIndex:a.zIndex}),this.handles[e]=".ui-resizable-"+e,this.element.append(o);this._renderAxis=function(e){var i,s,n,o;e=e||this.element;for(i in this.handles)this.handles[i].constructor===String?this.handles[i]=this.element.children(this.handles[i]).first().show():(this.handles[i].jquery||this.handles[i].nodeType)&&(this.handles[i]=t(this.handles[i]),this._on(this.handles[i],{mousedown:r._mouseDown})),this.elementIsWrapper&&this.originalElement[0].nodeName.match(/^(textarea|input|select|button)$/i)&&(s=t(this.handles[i],this.element),o=/sw|ne|nw|se|n|s/.test(i)?s.outerHeight():s.outerWidth(),n=["padding",/ne|nw|n/.test(i)?"Top":/se|sw|s/.test(i)?"Bottom":/^e$/.test(i)?"Right":"Left"].join(""),e.css(n,o),this._proportionallyResize()),this._handles=this._handles.add(this.handles[i])},this._renderAxis(this.element),this._handles=this._handles.add(this.element.find(".ui-resizable-handle")),this._handles.disableSelection(),this._handles.on("mouseover",function(){r.resizing||(this.className&&(o=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i)),r.axis=o&&o[1]?o[1]:"se")}),a.autoHide&&(this._handles.hide(),this._addClass("ui-resizable-autohide"))},_removeHandles:function(){this._handles.remove()},_mouseCapture:function(e){var i,s,n=!1;for(i in this.handles)s=t(this.handles[i])[0],(s===e.target||t.contains(s,e.target))&&(n=!0);return!this.options.disabled&&n},_mouseStart:function(e){var i,s,n,o=this.options,a=this.element;return this.resizing=!0,this._renderProxy(),i=this._num(this.helper.css("left")),s=this._num(this.helper.css("top")),o.containment&&(i+=t(o.containment).scrollLeft()||0,s+=t(o.containment).scrollTop()||0),this.offset=this.helper.offset(),this.position={left:i,top:s},this.size=this._helper?{width:this.helper.width(),height:this.helper.height()}:{width:a.width(),height:a.height()},this.originalSize=this._helper?{width:a.outerWidth(),height:a.outerHeight()}:{width:a.width(),height:a.height()},this.sizeDiff={width:a.outerWidth()-a.width(),height:a.outerHeight()-a.height()},this.originalPosition={left:i,top:s},this.originalMousePosition={left:e.pageX,top:e.pageY},this.aspectRatio="number"==typeof o.aspectRatio?o.aspectRatio:this.originalSize.width/this.originalSize.height||1,n=t(".ui-resizable-"+this.axis).css("cursor"),t("body").css("cursor","auto"===n?this.axis+"-resize":n),this._addClass("ui-resizable-resizing"),this._propagate("start",e),!0},_mouseDrag:function(e){var i,s,n=this.originalMousePosition,o=this.axis,a=e.pageX-n.left||0,r=e.pageY-n.top||0,h=this._change[o];return this._updatePrevProperties(),h?(i=h.apply(this,[e,a,r]),this._updateVirtualBoundaries(e.shiftKey),(this._aspectRatio||e.shiftKey)&&(i=this._updateRatio(i,e)),i=this._respectSize(i,e),this._updateCache(i),this._propagate("resize",e),s=this._applyChanges(),!this._helper&&this._proportionallyResizeElements.length&&this._proportionallyResize(),t.isEmptyObject(s)||(this._updatePrevProperties(),this._trigger("resize",e,this.ui()),this._applyChanges()),!1):!1},_mouseStop:function(e){this.resizing=!1;var i,s,n,o,a,r,h,l=this.options,c=this;return this._helper&&(i=this._proportionallyResizeElements,s=i.length&&/textarea/i.test(i[0].nodeName),n=s&&this._hasScroll(i[0],"left")?0:c.sizeDiff.height,o=s?0:c.sizeDiff.width,a={width:c.helper.width()-o,height:c.helper.height()-n},r=parseFloat(c.element.css("left"))+(c.position.left-c.originalPosition.left)||null,h=parseFloat(c.element.css("top"))+(c.position.top-c.originalPosition.top)||null,l.animate||this.element.css(t.extend(a,{top:h,left:r})),c.helper.height(c.size.height),c.helper.width(c.size.width),this._helper&&!l.animate&&this._proportionallyResize()),t("body").css("cursor","auto"),this._removeClass("ui-resizable-resizing"),this._propagate("stop",e),this._helper&&this.helper.remove(),!1},_updatePrevProperties:function(){this.prevPosition={top:this.position.top,left:this.position.left},this.prevSize={width:this.size.width,height:this.size.height}},_applyChanges:function(){var t={};return this.position.top!==this.prevPosition.top&&(t.top=this.position.top+"px"),this.position.left!==this.prevPosition.left&&(t.left=this.position.left+"px"),this.size.width!==this.prevSize.width&&(t.width=this.size.width+"px"),this.size.height!==this.prevSize.height&&(t.height=this.size.height+"px"),this.helper.css(t),t},_updateVirtualBoundaries:function(t){var e,i,s,n,o,a=this.options;o={minWidth:this._isNumber(a.minWidth)?a.minWidth:0,maxWidth:this._isNumber(a.maxWidth)?a.maxWidth:1/0,minHeight:this._isNumber(a.minHeight)?a.minHeight:0,maxHeight:this._isNumber(a.maxHeight)?a.maxHeight:1/0},(this._aspectRatio||t)&&(e=o.minHeight*this.aspectRatio,s=o.minWidth/this.aspectRatio,i=o.maxHeight*this.aspectRatio,n=o.maxWidth/this.aspectRatio,e>o.minWidth&&(o.minWidth=e),s>o.minHeight&&(o.minHeight=s),o.maxWidth>i&&(o.maxWidth=i),o.maxHeight>n&&(o.maxHeight=n)),this._vBoundaries=o},_updateCache:function(t){this.offset=this.helper.offset(),this._isNumber(t.left)&&(this.position.left=t.left),this._isNumber(t.top)&&(this.position.top=t.top),this._isNumber(t.height)&&(this.size.height=t.height),this._isNumber(t.width)&&(this.size.width=t.width)},_updateRatio:function(t){var e=this.position,i=this.size,s=this.axis;return this._isNumber(t.height)?t.width=t.height*this.aspectRatio:this._isNumber(t.width)&&(t.height=t.width/this.aspectRatio),"sw"===s&&(t.left=e.left+(i.width-t.width),t.top=null),"nw"===s&&(t.top=e.top+(i.height-t.height),t.left=e.left+(i.width-t.width)),t},_respectSize:function(t){var e=this._vBoundaries,i=this.axis,s=this._isNumber(t.width)&&e.maxWidth&&e.maxWidth<t.width,n=this._isNumber(t.height)&&e.maxHeight&&e.maxHeight<t.height,o=this._isNumber(t.width)&&e.minWidth&&e.minWidth>t.width,a=this._isNumber(t.height)&&e.minHeight&&e.minHeight>t.height,r=this.originalPosition.left+this.originalSize.width,h=this.originalPosition.top+this.originalSize.height,l=/sw|nw|w/.test(i),c=/nw|ne|n/.test(i);return o&&(t.width=e.minWidth),a&&(t.height=e.minHeight),s&&(t.width=e.maxWidth),n&&(t.height=e.maxHeight),o&&l&&(t.left=r-e.minWidth),s&&l&&(t.left=r-e.maxWidth),a&&c&&(t.top=h-e.minHeight),n&&c&&(t.top=h-e.maxHeight),t.width||t.height||t.left||!t.top?t.width||t.height||t.top||!t.left||(t.left=null):t.top=null,t},_getPaddingPlusBorderDimensions:function(t){for(var e=0,i=[],s=[t.css("borderTopWidth"),t.css("borderRightWidth"),t.css("borderBottomWidth"),t.css("borderLeftWidth")],n=[t.css("paddingTop"),t.css("paddingRight"),t.css("paddingBottom"),t.css("paddingLeft")];4>e;e++)i[e]=parseFloat(s[e])||0,i[e]+=parseFloat(n[e])||0;return{height:i[0]+i[2],width:i[1]+i[3]}},_proportionallyResize:function(){if(this._proportionallyResizeElements.length)for(var t,e=0,i=this.helper||this.element;this._proportionallyResizeElements.length>e;e++)t=this._proportionallyResizeElements[e],this.outerDimensions||(this.outerDimensions=this._getPaddingPlusBorderDimensions(t)),t.css({height:i.height()-this.outerDimensions.height||0,width:i.width()-this.outerDimensions.width||0})},_renderProxy:function(){var e=this.element,i=this.options;this.elementOffset=e.offset(),this._helper?(this.helper=this.helper||t("<div style='overflow:hidden;'></div>"),this._addClass(this.helper,this._helper),this.helper.css({width:this.element.outerWidth(),height:this.element.outerHeight(),position:"absolute",left:this.elementOffset.left+"px",top:this.elementOffset.top+"px",zIndex:++i.zIndex}),this.helper.appendTo("body").disableSelection()):this.helper=this.element},_change:{e:function(t,e){return{width:this.originalSize.width+e}},w:function(t,e){var i=this.originalSize,s=this.originalPosition;return{left:s.left+e,width:i.width-e}},n:function(t,e,i){var s=this.originalSize,n=this.originalPosition;return{top:n.top+i,height:s.height-i}},s:function(t,e,i){return{height:this.originalSize.height+i}},se:function(e,i,s){return t.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[e,i,s]))},sw:function(e,i,s){return t.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[e,i,s]))},ne:function(e,i,s){return t.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[e,i,s]))},nw:function(e,i,s){return t.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[e,i,s]))}},_propagate:function(e,i){t.ui.plugin.call(this,e,[i,this.ui()]),"resize"!==e&&this._trigger(e,i,this.ui())},plugins:{},ui:function(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition}}}),t.ui.plugin.add("resizable","animate",{stop:function(e){var i=t(this).resizable("instance"),s=i.options,n=i._proportionallyResizeElements,o=n.length&&/textarea/i.test(n[0].nodeName),a=o&&i._hasScroll(n[0],"left")?0:i.sizeDiff.height,r=o?0:i.sizeDiff.width,h={width:i.size.width-r,height:i.size.height-a},l=parseFloat(i.element.css("left"))+(i.position.left-i.originalPosition.left)||null,c=parseFloat(i.element.css("top"))+(i.position.top-i.originalPosition.top)||null;i.element.animate(t.extend(h,c&&l?{top:c,left:l}:{}),{duration:s.animateDuration,easing:s.animateEasing,step:function(){var s={width:parseFloat(i.element.css("width")),height:parseFloat(i.element.css("height")),top:parseFloat(i.element.css("top")),left:parseFloat(i.element.css("left"))};n&&n.length&&t(n[0]).css({width:s.width,height:s.height}),i._updateCache(s),i._propagate("resize",e)}})}}),t.ui.plugin.add("resizable","containment",{start:function(){var e,i,s,n,o,a,r,h=t(this).resizable("instance"),l=h.options,c=h.element,u=l.containment,d=u instanceof t?u.get(0):/parent/.test(u)?c.parent().get(0):u;d&&(h.containerElement=t(d),/document/.test(u)||u===document?(h.containerOffset={left:0,top:0},h.containerPosition={left:0,top:0},h.parentData={element:t(document),left:0,top:0,width:t(document).width(),height:t(document).height()||document.body.parentNode.scrollHeight}):(e=t(d),i=[],t(["Top","Right","Left","Bottom"]).each(function(t,s){i[t]=h._num(e.css("padding"+s))}),h.containerOffset=e.offset(),h.containerPosition=e.position(),h.containerSize={height:e.innerHeight()-i[3],width:e.innerWidth()-i[1]},s=h.containerOffset,n=h.containerSize.height,o=h.containerSize.width,a=h._hasScroll(d,"left")?d.scrollWidth:o,r=h._hasScroll(d)?d.scrollHeight:n,h.parentData={element:d,left:s.left,top:s.top,width:a,height:r}))},resize:function(e){var i,s,n,o,a=t(this).resizable("instance"),r=a.options,h=a.containerOffset,l=a.position,c=a._aspectRatio||e.shiftKey,u={top:0,left:0},d=a.containerElement,p=!0;d[0]!==document&&/static/.test(d.css("position"))&&(u=h),l.left<(a._helper?h.left:0)&&(a.size.width=a.size.width+(a._helper?a.position.left-h.left:a.position.left-u.left),c&&(a.size.height=a.size.width/a.aspectRatio,p=!1),a.position.left=r.helper?h.left:0),l.top<(a._helper?h.top:0)&&(a.size.height=a.size.height+(a._helper?a.position.top-h.top:a.position.top),c&&(a.size.width=a.size.height*a.aspectRatio,p=!1),a.position.top=a._helper?h.top:0),n=a.containerElement.get(0)===a.element.parent().get(0),o=/relative|absolute/.test(a.containerElement.css("position")),n&&o?(a.offset.left=a.parentData.left+a.position.left,a.offset.top=a.parentData.top+a.position.top):(a.offset.left=a.element.offset().left,a.offset.top=a.element.offset().top),i=Math.abs(a.sizeDiff.width+(a._helper?a.offset.left-u.left:a.offset.left-h.left)),s=Math.abs(a.sizeDiff.height+(a._helper?a.offset.top-u.top:a.offset.top-h.top)),i+a.size.width>=a.parentData.width&&(a.size.width=a.parentData.width-i,c&&(a.size.height=a.size.width/a.aspectRatio,p=!1)),s+a.size.height>=a.parentData.height&&(a.size.height=a.parentData.height-s,c&&(a.size.width=a.size.height*a.aspectRatio,p=!1)),p||(a.position.left=a.prevPosition.left,a.position.top=a.prevPosition.top,a.size.width=a.prevSize.width,a.size.height=a.prevSize.height)},stop:function(){var e=t(this).resizable("instance"),i=e.options,s=e.containerOffset,n=e.containerPosition,o=e.containerElement,a=t(e.helper),r=a.offset(),h=a.outerWidth()-e.sizeDiff.width,l=a.outerHeight()-e.sizeDiff.height;e._helper&&!i.animate&&/relative/.test(o.css("position"))&&t(this).css({left:r.left-n.left-s.left,width:h,height:l}),e._helper&&!i.animate&&/static/.test(o.css("position"))&&t(this).css({left:r.left-n.left-s.left,width:h,height:l})}}),t.ui.plugin.add("resizable","alsoResize",{start:function(){var e=t(this).resizable("instance"),i=e.options;t(i.alsoResize).each(function(){var e=t(this);e.data("ui-resizable-alsoresize",{width:parseFloat(e.width()),height:parseFloat(e.height()),left:parseFloat(e.css("left")),top:parseFloat(e.css("top"))})})},resize:function(e,i){var s=t(this).resizable("instance"),n=s.options,o=s.originalSize,a=s.originalPosition,r={height:s.size.height-o.height||0,width:s.size.width-o.width||0,top:s.position.top-a.top||0,left:s.position.left-a.left||0};t(n.alsoResize).each(function(){var e=t(this),s=t(this).data("ui-resizable-alsoresize"),n={},o=e.parents(i.originalElement[0]).length?["width","height"]:["width","height","top","left"];t.each(o,function(t,e){var i=(s[e]||0)+(r[e]||0);i&&i>=0&&(n[e]=i||null)}),e.css(n)})},stop:function(){t(this).removeData("ui-resizable-alsoresize")}}),t.ui.plugin.add("resizable","ghost",{start:function(){var e=t(this).resizable("instance"),i=e.size;e.ghost=e.originalElement.clone(),e.ghost.css({opacity:.25,display:"block",position:"relative",height:i.height,width:i.width,margin:0,left:0,top:0}),e._addClass(e.ghost,"ui-resizable-ghost"),t.uiBackCompat!==!1&&"string"==typeof e.options.ghost&&e.ghost.addClass(this.options.ghost),e.ghost.appendTo(e.helper)},resize:function(){var e=t(this).resizable("instance");e.ghost&&e.ghost.css({position:"relative",height:e.size.height,width:e.size.width})},stop:function(){var e=t(this).resizable("instance");e.ghost&&e.helper&&e.helper.get(0).removeChild(e.ghost.get(0))}}),t.ui.plugin.add("resizable","grid",{resize:function(){var e,i=t(this).resizable("instance"),s=i.options,n=i.size,o=i.originalSize,a=i.originalPosition,r=i.axis,h="number"==typeof s.grid?[s.grid,s.grid]:s.grid,l=h[0]||1,c=h[1]||1,u=Math.round((n.width-o.width)/l)*l,d=Math.round((n.height-o.height)/c)*c,p=o.width+u,f=o.height+d,g=s.maxWidth&&p>s.maxWidth,m=s.maxHeight&&f>s.maxHeight,_=s.minWidth&&s.minWidth>p,v=s.minHeight&&s.minHeight>f;s.grid=h,_&&(p+=l),v&&(f+=c),g&&(p-=l),m&&(f-=c),/^(se|s|e)$/.test(r)?(i.size.width=p,i.size.height=f):/^(ne)$/.test(r)?(i.size.width=p,i.size.height=f,i.position.top=a.top-d):/^(sw)$/.test(r)?(i.size.width=p,i.size.height=f,i.position.left=a.left-u):((0>=f-c||0>=p-l)&&(e=i._getPaddingPlusBorderDimensions(this)),f-c>0?(i.size.height=f,i.position.top=a.top-d):(f=c-e.height,i.size.height=f,i.position.top=a.top+o.height-f),p-l>0?(i.size.width=p,i.position.left=a.left-u):(p=l-e.width,i.size.width=p,i.position.left=a.left+o.width-p))}}),t.ui.resizable,t.widget("ui.dialog",{version:"1.12.1",options:{appendTo:"body",autoOpen:!0,buttons:[],classes:{"ui-dialog":"ui-corner-all","ui-dialog-titlebar":"ui-corner-all"},closeOnEscape:!0,closeText:"Close",draggable:!0,hide:null,height:"auto",maxHeight:null,maxWidth:null,minHeight:150,minWidth:150,modal:!1,position:{my:"center",at:"center",of:window,collision:"fit",using:function(e){var i=t(this).css(e).offset().top;0>i&&t(this).css("top",e.top-i)}},resizable:!0,show:null,title:null,width:300,beforeClose:null,close:null,drag:null,dragStart:null,dragStop:null,focus:null,open:null,resize:null,resizeStart:null,resizeStop:null},sizeRelatedOptions:{buttons:!0,height:!0,maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0,width:!0},resizableRelatedOptions:{maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0},_create:function(){this.originalCss={display:this.element[0].style.display,width:this.element[0].style.width,minHeight:this.element[0].style.minHeight,maxHeight:this.element[0].style.maxHeight,height:this.element[0].style.height},this.originalPosition={parent:this.element.parent(),index:this.element.parent().children().index(this.element)},this.originalTitle=this.element.attr("title"),null==this.options.title&&null!=this.originalTitle&&(this.options.title=this.originalTitle),this.options.disabled&&(this.options.disabled=!1),this._createWrapper(),this.element.show().removeAttr("title").appendTo(this.uiDialog),this._addClass("ui-dialog-content","ui-widget-content"),this._createTitlebar(),this._createButtonPane(),this.options.draggable&&t.fn.draggable&&this._makeDraggable(),this.options.resizable&&t.fn.resizable&&this._makeResizable(),this._isOpen=!1,this._trackFocus()},_init:function(){this.options.autoOpen&&this.open()},_appendTo:function(){var e=this.options.appendTo;return e&&(e.jquery||e.nodeType)?t(e):this.document.find(e||"body").eq(0)},_destroy:function(){var t,e=this.originalPosition;this._untrackInstance(),this._destroyOverlay(),this.element.removeUniqueId().css(this.originalCss).detach(),this.uiDialog.remove(),this.originalTitle&&this.element.attr("title",this.originalTitle),t=e.parent.children().eq(e.index),t.length&&t[0]!==this.element[0]?t.before(this.element):e.parent.append(this.element)},widget:function(){return this.uiDialog
},disable:t.noop,enable:t.noop,close:function(e){var i=this;this._isOpen&&this._trigger("beforeClose",e)!==!1&&(this._isOpen=!1,this._focusedElement=null,this._destroyOverlay(),this._untrackInstance(),this.opener.filter(":focusable").trigger("focus").length||t.ui.safeBlur(t.ui.safeActiveElement(this.document[0])),this._hide(this.uiDialog,this.options.hide,function(){i._trigger("close",e)}))},isOpen:function(){return this._isOpen},moveToTop:function(){this._moveToTop()},_moveToTop:function(e,i){var s=!1,n=this.uiDialog.siblings(".ui-front:visible").map(function(){return+t(this).css("z-index")}).get(),o=Math.max.apply(null,n);return o>=+this.uiDialog.css("z-index")&&(this.uiDialog.css("z-index",o+1),s=!0),s&&!i&&this._trigger("focus",e),s},open:function(){var e=this;return this._isOpen?(this._moveToTop()&&this._focusTabbable(),void 0):(this._isOpen=!0,this.opener=t(t.ui.safeActiveElement(this.document[0])),this._size(),this._position(),this._createOverlay(),this._moveToTop(null,!0),this.overlay&&this.overlay.css("z-index",this.uiDialog.css("z-index")-1),this._show(this.uiDialog,this.options.show,function(){e._focusTabbable(),e._trigger("focus")}),this._makeFocusTarget(),this._trigger("open"),void 0)},_focusTabbable:function(){var t=this._focusedElement;t||(t=this.element.find("[autofocus]")),t.length||(t=this.element.find(":tabbable")),t.length||(t=this.uiDialogButtonPane.find(":tabbable")),t.length||(t=this.uiDialogTitlebarClose.filter(":tabbable")),t.length||(t=this.uiDialog),t.eq(0).trigger("focus")},_keepFocus:function(e){function i(){var e=t.ui.safeActiveElement(this.document[0]),i=this.uiDialog[0]===e||t.contains(this.uiDialog[0],e);i||this._focusTabbable()}e.preventDefault(),i.call(this),this._delay(i)},_createWrapper:function(){this.uiDialog=t("<div>").hide().attr({tabIndex:-1,role:"dialog"}).appendTo(this._appendTo()),this._addClass(this.uiDialog,"ui-dialog","ui-widget ui-widget-content ui-front"),this._on(this.uiDialog,{keydown:function(e){if(this.options.closeOnEscape&&!e.isDefaultPrevented()&&e.keyCode&&e.keyCode===t.ui.keyCode.ESCAPE)return e.preventDefault(),this.close(e),void 0;if(e.keyCode===t.ui.keyCode.TAB&&!e.isDefaultPrevented()){var i=this.uiDialog.find(":tabbable"),s=i.filter(":first"),n=i.filter(":last");e.target!==n[0]&&e.target!==this.uiDialog[0]||e.shiftKey?e.target!==s[0]&&e.target!==this.uiDialog[0]||!e.shiftKey||(this._delay(function(){n.trigger("focus")}),e.preventDefault()):(this._delay(function(){s.trigger("focus")}),e.preventDefault())}},mousedown:function(t){this._moveToTop(t)&&this._focusTabbable()}}),this.element.find("[aria-describedby]").length||this.uiDialog.attr({"aria-describedby":this.element.uniqueId().attr("id")})},_createTitlebar:function(){var e;this.uiDialogTitlebar=t("<div>"),this._addClass(this.uiDialogTitlebar,"ui-dialog-titlebar","ui-widget-header ui-helper-clearfix"),this._on(this.uiDialogTitlebar,{mousedown:function(e){t(e.target).closest(".ui-dialog-titlebar-close")||this.uiDialog.trigger("focus")}}),this.uiDialogTitlebarClose=t("<button type='button'></button>").button({label:t("<a>").text(this.options.closeText).html(),icon:"ui-icon-closethick",showLabel:!1}).appendTo(this.uiDialogTitlebar),this._addClass(this.uiDialogTitlebarClose,"ui-dialog-titlebar-close"),this._on(this.uiDialogTitlebarClose,{click:function(t){t.preventDefault(),this.close(t)}}),e=t("<span>").uniqueId().prependTo(this.uiDialogTitlebar),this._addClass(e,"ui-dialog-title"),this._title(e),this.uiDialogTitlebar.prependTo(this.uiDialog),this.uiDialog.attr({"aria-labelledby":e.attr("id")})},_title:function(t){this.options.title?t.text(this.options.title):t.html("&#160;")},_createButtonPane:function(){this.uiDialogButtonPane=t("<div>"),this._addClass(this.uiDialogButtonPane,"ui-dialog-buttonpane","ui-widget-content ui-helper-clearfix"),this.uiButtonSet=t("<div>").appendTo(this.uiDialogButtonPane),this._addClass(this.uiButtonSet,"ui-dialog-buttonset"),this._createButtons()},_createButtons:function(){var e=this,i=this.options.buttons;return this.uiDialogButtonPane.remove(),this.uiButtonSet.empty(),t.isEmptyObject(i)||t.isArray(i)&&!i.length?(this._removeClass(this.uiDialog,"ui-dialog-buttons"),void 0):(t.each(i,function(i,s){var n,o;s=t.isFunction(s)?{click:s,text:i}:s,s=t.extend({type:"button"},s),n=s.click,o={icon:s.icon,iconPosition:s.iconPosition,showLabel:s.showLabel,icons:s.icons,text:s.text},delete s.click,delete s.icon,delete s.iconPosition,delete s.showLabel,delete s.icons,"boolean"==typeof s.text&&delete s.text,t("<button></button>",s).button(o).appendTo(e.uiButtonSet).on("click",function(){n.apply(e.element[0],arguments)})}),this._addClass(this.uiDialog,"ui-dialog-buttons"),this.uiDialogButtonPane.appendTo(this.uiDialog),void 0)},_makeDraggable:function(){function e(t){return{position:t.position,offset:t.offset}}var i=this,s=this.options;this.uiDialog.draggable({cancel:".ui-dialog-content, .ui-dialog-titlebar-close",handle:".ui-dialog-titlebar",containment:"document",start:function(s,n){i._addClass(t(this),"ui-dialog-dragging"),i._blockFrames(),i._trigger("dragStart",s,e(n))},drag:function(t,s){i._trigger("drag",t,e(s))},stop:function(n,o){var a=o.offset.left-i.document.scrollLeft(),r=o.offset.top-i.document.scrollTop();s.position={my:"left top",at:"left"+(a>=0?"+":"")+a+" "+"top"+(r>=0?"+":"")+r,of:i.window},i._removeClass(t(this),"ui-dialog-dragging"),i._unblockFrames(),i._trigger("dragStop",n,e(o))}})},_makeResizable:function(){function e(t){return{originalPosition:t.originalPosition,originalSize:t.originalSize,position:t.position,size:t.size}}var i=this,s=this.options,n=s.resizable,o=this.uiDialog.css("position"),a="string"==typeof n?n:"n,e,s,w,se,sw,ne,nw";this.uiDialog.resizable({cancel:".ui-dialog-content",containment:"document",alsoResize:this.element,maxWidth:s.maxWidth,maxHeight:s.maxHeight,minWidth:s.minWidth,minHeight:this._minHeight(),handles:a,start:function(s,n){i._addClass(t(this),"ui-dialog-resizing"),i._blockFrames(),i._trigger("resizeStart",s,e(n))},resize:function(t,s){i._trigger("resize",t,e(s))},stop:function(n,o){var a=i.uiDialog.offset(),r=a.left-i.document.scrollLeft(),h=a.top-i.document.scrollTop();s.height=i.uiDialog.height(),s.width=i.uiDialog.width(),s.position={my:"left top",at:"left"+(r>=0?"+":"")+r+" "+"top"+(h>=0?"+":"")+h,of:i.window},i._removeClass(t(this),"ui-dialog-resizing"),i._unblockFrames(),i._trigger("resizeStop",n,e(o))}}).css("position",o)},_trackFocus:function(){this._on(this.widget(),{focusin:function(e){this._makeFocusTarget(),this._focusedElement=t(e.target)}})},_makeFocusTarget:function(){this._untrackInstance(),this._trackingInstances().unshift(this)},_untrackInstance:function(){var e=this._trackingInstances(),i=t.inArray(this,e);-1!==i&&e.splice(i,1)},_trackingInstances:function(){var t=this.document.data("ui-dialog-instances");return t||(t=[],this.document.data("ui-dialog-instances",t)),t},_minHeight:function(){var t=this.options;return"auto"===t.height?t.minHeight:Math.min(t.minHeight,t.height)},_position:function(){var t=this.uiDialog.is(":visible");t||this.uiDialog.show(),this.uiDialog.position(this.options.position),t||this.uiDialog.hide()},_setOptions:function(e){var i=this,s=!1,n={};t.each(e,function(t,e){i._setOption(t,e),t in i.sizeRelatedOptions&&(s=!0),t in i.resizableRelatedOptions&&(n[t]=e)}),s&&(this._size(),this._position()),this.uiDialog.is(":data(ui-resizable)")&&this.uiDialog.resizable("option",n)},_setOption:function(e,i){var s,n,o=this.uiDialog;"disabled"!==e&&(this._super(e,i),"appendTo"===e&&this.uiDialog.appendTo(this._appendTo()),"buttons"===e&&this._createButtons(),"closeText"===e&&this.uiDialogTitlebarClose.button({label:t("<a>").text(""+this.options.closeText).html()}),"draggable"===e&&(s=o.is(":data(ui-draggable)"),s&&!i&&o.draggable("destroy"),!s&&i&&this._makeDraggable()),"position"===e&&this._position(),"resizable"===e&&(n=o.is(":data(ui-resizable)"),n&&!i&&o.resizable("destroy"),n&&"string"==typeof i&&o.resizable("option","handles",i),n||i===!1||this._makeResizable()),"title"===e&&this._title(this.uiDialogTitlebar.find(".ui-dialog-title")))},_size:function(){var t,e,i,s=this.options;this.element.show().css({width:"auto",minHeight:0,maxHeight:"none",height:0}),s.minWidth>s.width&&(s.width=s.minWidth),t=this.uiDialog.css({height:"auto",width:s.width}).outerHeight(),e=Math.max(0,s.minHeight-t),i="number"==typeof s.maxHeight?Math.max(0,s.maxHeight-t):"none","auto"===s.height?this.element.css({minHeight:e,maxHeight:i,height:"auto"}):this.element.height(Math.max(0,s.height-t)),this.uiDialog.is(":data(ui-resizable)")&&this.uiDialog.resizable("option","minHeight",this._minHeight())},_blockFrames:function(){this.iframeBlocks=this.document.find("iframe").map(function(){var e=t(this);return t("<div>").css({position:"absolute",width:e.outerWidth(),height:e.outerHeight()}).appendTo(e.parent()).offset(e.offset())[0]})},_unblockFrames:function(){this.iframeBlocks&&(this.iframeBlocks.remove(),delete this.iframeBlocks)},_allowInteraction:function(e){return t(e.target).closest(".ui-dialog").length?!0:!!t(e.target).closest(".ui-datepicker").length},_createOverlay:function(){if(this.options.modal){var e=!0;this._delay(function(){e=!1}),this.document.data("ui-dialog-overlays")||this._on(this.document,{focusin:function(t){e||this._allowInteraction(t)||(t.preventDefault(),this._trackingInstances()[0]._focusTabbable())}}),this.overlay=t("<div>").appendTo(this._appendTo()),this._addClass(this.overlay,null,"ui-widget-overlay ui-front"),this._on(this.overlay,{mousedown:"_keepFocus"}),this.document.data("ui-dialog-overlays",(this.document.data("ui-dialog-overlays")||0)+1)}},_destroyOverlay:function(){if(this.options.modal&&this.overlay){var t=this.document.data("ui-dialog-overlays")-1;t?this.document.data("ui-dialog-overlays",t):(this._off(this.document,"focusin"),this.document.removeData("ui-dialog-overlays")),this.overlay.remove(),this.overlay=null}}}),t.uiBackCompat!==!1&&t.widget("ui.dialog",t.ui.dialog,{options:{dialogClass:""},_createWrapper:function(){this._super(),this.uiDialog.addClass(this.options.dialogClass)},_setOption:function(t,e){"dialogClass"===t&&this.uiDialog.removeClass(this.options.dialogClass).addClass(e),this._superApply(arguments)}}),t.ui.dialog,t.widget("ui.droppable",{version:"1.12.1",widgetEventPrefix:"drop",options:{accept:"*",addClasses:!0,greedy:!1,scope:"default",tolerance:"intersect",activate:null,deactivate:null,drop:null,out:null,over:null},_create:function(){var e,i=this.options,s=i.accept;this.isover=!1,this.isout=!0,this.accept=t.isFunction(s)?s:function(t){return t.is(s)},this.proportions=function(){return arguments.length?(e=arguments[0],void 0):e?e:e={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight}},this._addToManager(i.scope),i.addClasses&&this._addClass("ui-droppable")},_addToManager:function(e){t.ui.ddmanager.droppables[e]=t.ui.ddmanager.droppables[e]||[],t.ui.ddmanager.droppables[e].push(this)},_splice:function(t){for(var e=0;t.length>e;e++)t[e]===this&&t.splice(e,1)},_destroy:function(){var e=t.ui.ddmanager.droppables[this.options.scope];this._splice(e)},_setOption:function(e,i){if("accept"===e)this.accept=t.isFunction(i)?i:function(t){return t.is(i)};else if("scope"===e){var s=t.ui.ddmanager.droppables[this.options.scope];this._splice(s),this._addToManager(i)}this._super(e,i)},_activate:function(e){var i=t.ui.ddmanager.current;this._addActiveClass(),i&&this._trigger("activate",e,this.ui(i))},_deactivate:function(e){var i=t.ui.ddmanager.current;this._removeActiveClass(),i&&this._trigger("deactivate",e,this.ui(i))},_over:function(e){var i=t.ui.ddmanager.current;i&&(i.currentItem||i.element)[0]!==this.element[0]&&this.accept.call(this.element[0],i.currentItem||i.element)&&(this._addHoverClass(),this._trigger("over",e,this.ui(i)))},_out:function(e){var i=t.ui.ddmanager.current;i&&(i.currentItem||i.element)[0]!==this.element[0]&&this.accept.call(this.element[0],i.currentItem||i.element)&&(this._removeHoverClass(),this._trigger("out",e,this.ui(i)))},_drop:function(e,i){var s=i||t.ui.ddmanager.current,n=!1;return s&&(s.currentItem||s.element)[0]!==this.element[0]?(this.element.find(":data(ui-droppable)").not(".ui-draggable-dragging").each(function(){var i=t(this).droppable("instance");return i.options.greedy&&!i.options.disabled&&i.options.scope===s.options.scope&&i.accept.call(i.element[0],s.currentItem||s.element)&&v(s,t.extend(i,{offset:i.element.offset()}),i.options.tolerance,e)?(n=!0,!1):void 0}),n?!1:this.accept.call(this.element[0],s.currentItem||s.element)?(this._removeActiveClass(),this._removeHoverClass(),this._trigger("drop",e,this.ui(s)),this.element):!1):!1},ui:function(t){return{draggable:t.currentItem||t.element,helper:t.helper,position:t.position,offset:t.positionAbs}},_addHoverClass:function(){this._addClass("ui-droppable-hover")},_removeHoverClass:function(){this._removeClass("ui-droppable-hover")},_addActiveClass:function(){this._addClass("ui-droppable-active")},_removeActiveClass:function(){this._removeClass("ui-droppable-active")}});var v=t.ui.intersect=function(){function t(t,e,i){return t>=e&&e+i>t}return function(e,i,s,n){if(!i.offset)return!1;var o=(e.positionAbs||e.position.absolute).left+e.margins.left,a=(e.positionAbs||e.position.absolute).top+e.margins.top,r=o+e.helperProportions.width,h=a+e.helperProportions.height,l=i.offset.left,c=i.offset.top,u=l+i.proportions().width,d=c+i.proportions().height;switch(s){case"fit":return o>=l&&u>=r&&a>=c&&d>=h;case"intersect":return o+e.helperProportions.width/2>l&&u>r-e.helperProportions.width/2&&a+e.helperProportions.height/2>c&&d>h-e.helperProportions.height/2;case"pointer":return t(n.pageY,c,i.proportions().height)&&t(n.pageX,l,i.proportions().width);case"touch":return(a>=c&&d>=a||h>=c&&d>=h||c>a&&h>d)&&(o>=l&&u>=o||r>=l&&u>=r||l>o&&r>u);default:return!1}}}();t.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function(e,i){var s,n,o=t.ui.ddmanager.droppables[e.options.scope]||[],a=i?i.type:null,r=(e.currentItem||e.element).find(":data(ui-droppable)").addBack();t:for(s=0;o.length>s;s++)if(!(o[s].options.disabled||e&&!o[s].accept.call(o[s].element[0],e.currentItem||e.element))){for(n=0;r.length>n;n++)if(r[n]===o[s].element[0]){o[s].proportions().height=0;continue t}o[s].visible="none"!==o[s].element.css("display"),o[s].visible&&("mousedown"===a&&o[s]._activate.call(o[s],i),o[s].offset=o[s].element.offset(),o[s].proportions({width:o[s].element[0].offsetWidth,height:o[s].element[0].offsetHeight}))}},drop:function(e,i){var s=!1;return t.each((t.ui.ddmanager.droppables[e.options.scope]||[]).slice(),function(){this.options&&(!this.options.disabled&&this.visible&&v(e,this,this.options.tolerance,i)&&(s=this._drop.call(this,i)||s),!this.options.disabled&&this.visible&&this.accept.call(this.element[0],e.currentItem||e.element)&&(this.isout=!0,this.isover=!1,this._deactivate.call(this,i)))}),s},dragStart:function(e,i){e.element.parentsUntil("body").on("scroll.droppable",function(){e.options.refreshPositions||t.ui.ddmanager.prepareOffsets(e,i)})},drag:function(e,i){e.options.refreshPositions&&t.ui.ddmanager.prepareOffsets(e,i),t.each(t.ui.ddmanager.droppables[e.options.scope]||[],function(){if(!this.options.disabled&&!this.greedyChild&&this.visible){var s,n,o,a=v(e,this,this.options.tolerance,i),r=!a&&this.isover?"isout":a&&!this.isover?"isover":null;r&&(this.options.greedy&&(n=this.options.scope,o=this.element.parents(":data(ui-droppable)").filter(function(){return t(this).droppable("instance").options.scope===n}),o.length&&(s=t(o[0]).droppable("instance"),s.greedyChild="isover"===r)),s&&"isover"===r&&(s.isover=!1,s.isout=!0,s._out.call(s,i)),this[r]=!0,this["isout"===r?"isover":"isout"]=!1,this["isover"===r?"_over":"_out"].call(this,i),s&&"isout"===r&&(s.isout=!1,s.isover=!0,s._over.call(s,i)))}})},dragStop:function(e,i){e.element.parentsUntil("body").off("scroll.droppable"),e.options.refreshPositions||t.ui.ddmanager.prepareOffsets(e,i)}},t.uiBackCompat!==!1&&t.widget("ui.droppable",t.ui.droppable,{options:{hoverClass:!1,activeClass:!1},_addActiveClass:function(){this._super(),this.options.activeClass&&this.element.addClass(this.options.activeClass)},_removeActiveClass:function(){this._super(),this.options.activeClass&&this.element.removeClass(this.options.activeClass)},_addHoverClass:function(){this._super(),this.options.hoverClass&&this.element.addClass(this.options.hoverClass)},_removeHoverClass:function(){this._super(),this.options.hoverClass&&this.element.removeClass(this.options.hoverClass)}}),t.ui.droppable,t.widget("ui.progressbar",{version:"1.12.1",options:{classes:{"ui-progressbar":"ui-corner-all","ui-progressbar-value":"ui-corner-left","ui-progressbar-complete":"ui-corner-right"},max:100,value:0,change:null,complete:null},min:0,_create:function(){this.oldValue=this.options.value=this._constrainedValue(),this.element.attr({role:"progressbar","aria-valuemin":this.min}),this._addClass("ui-progressbar","ui-widget ui-widget-content"),this.valueDiv=t("<div>").appendTo(this.element),this._addClass(this.valueDiv,"ui-progressbar-value","ui-widget-header"),this._refreshValue()},_destroy:function(){this.element.removeAttr("role aria-valuemin aria-valuemax aria-valuenow"),this.valueDiv.remove()},value:function(t){return void 0===t?this.options.value:(this.options.value=this._constrainedValue(t),this._refreshValue(),void 0)},_constrainedValue:function(t){return void 0===t&&(t=this.options.value),this.indeterminate=t===!1,"number"!=typeof t&&(t=0),this.indeterminate?!1:Math.min(this.options.max,Math.max(this.min,t))},_setOptions:function(t){var e=t.value;delete t.value,this._super(t),this.options.value=this._constrainedValue(e),this._refreshValue()},_setOption:function(t,e){"max"===t&&(e=Math.max(this.min,e)),this._super(t,e)},_setOptionDisabled:function(t){this._super(t),this.element.attr("aria-disabled",t),this._toggleClass(null,"ui-state-disabled",!!t)},_percentage:function(){return this.indeterminate?100:100*(this.options.value-this.min)/(this.options.max-this.min)},_refreshValue:function(){var e=this.options.value,i=this._percentage();this.valueDiv.toggle(this.indeterminate||e>this.min).width(i.toFixed(0)+"%"),this._toggleClass(this.valueDiv,"ui-progressbar-complete",null,e===this.options.max)._toggleClass("ui-progressbar-indeterminate",null,this.indeterminate),this.indeterminate?(this.element.removeAttr("aria-valuenow"),this.overlayDiv||(this.overlayDiv=t("<div>").appendTo(this.valueDiv),this._addClass(this.overlayDiv,"ui-progressbar-overlay"))):(this.element.attr({"aria-valuemax":this.options.max,"aria-valuenow":e}),this.overlayDiv&&(this.overlayDiv.remove(),this.overlayDiv=null)),this.oldValue!==e&&(this.oldValue=e,this._trigger("change")),e===this.options.max&&this._trigger("complete")}}),t.widget("ui.selectable",t.ui.mouse,{version:"1.12.1",options:{appendTo:"body",autoRefresh:!0,distance:0,filter:"*",tolerance:"touch",selected:null,selecting:null,start:null,stop:null,unselected:null,unselecting:null},_create:function(){var e=this;this._addClass("ui-selectable"),this.dragged=!1,this.refresh=function(){e.elementPos=t(e.element[0]).offset(),e.selectees=t(e.options.filter,e.element[0]),e._addClass(e.selectees,"ui-selectee"),e.selectees.each(function(){var i=t(this),s=i.offset(),n={left:s.left-e.elementPos.left,top:s.top-e.elementPos.top};t.data(this,"selectable-item",{element:this,$element:i,left:n.left,top:n.top,right:n.left+i.outerWidth(),bottom:n.top+i.outerHeight(),startselected:!1,selected:i.hasClass("ui-selected"),selecting:i.hasClass("ui-selecting"),unselecting:i.hasClass("ui-unselecting")})})},this.refresh(),this._mouseInit(),this.helper=t("<div>"),this._addClass(this.helper,"ui-selectable-helper")},_destroy:function(){this.selectees.removeData("selectable-item"),this._mouseDestroy()},_mouseStart:function(e){var i=this,s=this.options;this.opos=[e.pageX,e.pageY],this.elementPos=t(this.element[0]).offset(),this.options.disabled||(this.selectees=t(s.filter,this.element[0]),this._trigger("start",e),t(s.appendTo).append(this.helper),this.helper.css({left:e.pageX,top:e.pageY,width:0,height:0}),s.autoRefresh&&this.refresh(),this.selectees.filter(".ui-selected").each(function(){var s=t.data(this,"selectable-item");s.startselected=!0,e.metaKey||e.ctrlKey||(i._removeClass(s.$element,"ui-selected"),s.selected=!1,i._addClass(s.$element,"ui-unselecting"),s.unselecting=!0,i._trigger("unselecting",e,{unselecting:s.element}))}),t(e.target).parents().addBack().each(function(){var s,n=t.data(this,"selectable-item");return n?(s=!e.metaKey&&!e.ctrlKey||!n.$element.hasClass("ui-selected"),i._removeClass(n.$element,s?"ui-unselecting":"ui-selected")._addClass(n.$element,s?"ui-selecting":"ui-unselecting"),n.unselecting=!s,n.selecting=s,n.selected=s,s?i._trigger("selecting",e,{selecting:n.element}):i._trigger("unselecting",e,{unselecting:n.element}),!1):void 0}))},_mouseDrag:function(e){if(this.dragged=!0,!this.options.disabled){var i,s=this,n=this.options,o=this.opos[0],a=this.opos[1],r=e.pageX,h=e.pageY;return o>r&&(i=r,r=o,o=i),a>h&&(i=h,h=a,a=i),this.helper.css({left:o,top:a,width:r-o,height:h-a}),this.selectees.each(function(){var i=t.data(this,"selectable-item"),l=!1,c={};i&&i.element!==s.element[0]&&(c.left=i.left+s.elementPos.left,c.right=i.right+s.elementPos.left,c.top=i.top+s.elementPos.top,c.bottom=i.bottom+s.elementPos.top,"touch"===n.tolerance?l=!(c.left>r||o>c.right||c.top>h||a>c.bottom):"fit"===n.tolerance&&(l=c.left>o&&r>c.right&&c.top>a&&h>c.bottom),l?(i.selected&&(s._removeClass(i.$element,"ui-selected"),i.selected=!1),i.unselecting&&(s._removeClass(i.$element,"ui-unselecting"),i.unselecting=!1),i.selecting||(s._addClass(i.$element,"ui-selecting"),i.selecting=!0,s._trigger("selecting",e,{selecting:i.element}))):(i.selecting&&((e.metaKey||e.ctrlKey)&&i.startselected?(s._removeClass(i.$element,"ui-selecting"),i.selecting=!1,s._addClass(i.$element,"ui-selected"),i.selected=!0):(s._removeClass(i.$element,"ui-selecting"),i.selecting=!1,i.startselected&&(s._addClass(i.$element,"ui-unselecting"),i.unselecting=!0),s._trigger("unselecting",e,{unselecting:i.element}))),i.selected&&(e.metaKey||e.ctrlKey||i.startselected||(s._removeClass(i.$element,"ui-selected"),i.selected=!1,s._addClass(i.$element,"ui-unselecting"),i.unselecting=!0,s._trigger("unselecting",e,{unselecting:i.element})))))}),!1}},_mouseStop:function(e){var i=this;return this.dragged=!1,t(".ui-unselecting",this.element[0]).each(function(){var s=t.data(this,"selectable-item");i._removeClass(s.$element,"ui-unselecting"),s.unselecting=!1,s.startselected=!1,i._trigger("unselected",e,{unselected:s.element})}),t(".ui-selecting",this.element[0]).each(function(){var s=t.data(this,"selectable-item");i._removeClass(s.$element,"ui-selecting")._addClass(s.$element,"ui-selected"),s.selecting=!1,s.selected=!0,s.startselected=!0,i._trigger("selected",e,{selected:s.element})}),this._trigger("stop",e),this.helper.remove(),!1}}),t.widget("ui.selectmenu",[t.ui.formResetMixin,{version:"1.12.1",defaultElement:"<select>",options:{appendTo:null,classes:{"ui-selectmenu-button-open":"ui-corner-top","ui-selectmenu-button-closed":"ui-corner-all"},disabled:null,icons:{button:"ui-icon-triangle-1-s"},position:{my:"left top",at:"left bottom",collision:"none"},width:!1,change:null,close:null,focus:null,open:null,select:null},_create:function(){var e=this.element.uniqueId().attr("id");this.ids={element:e,button:e+"-button",menu:e+"-menu"},this._drawButton(),this._drawMenu(),this._bindFormResetHandler(),this._rendered=!1,this.menuItems=t()},_drawButton:function(){var e,i=this,s=this._parseOption(this.element.find("option:selected"),this.element[0].selectedIndex);this.labels=this.element.labels().attr("for",this.ids.button),this._on(this.labels,{click:function(t){this.button.focus(),t.preventDefault()}}),this.element.hide(),this.button=t("<span>",{tabindex:this.options.disabled?-1:0,id:this.ids.button,role:"combobox","aria-expanded":"false","aria-autocomplete":"list","aria-owns":this.ids.menu,"aria-haspopup":"true",title:this.element.attr("title")}).insertAfter(this.element),this._addClass(this.button,"ui-selectmenu-button ui-selectmenu-button-closed","ui-button ui-widget"),e=t("<span>").appendTo(this.button),this._addClass(e,"ui-selectmenu-icon","ui-icon "+this.options.icons.button),this.buttonItem=this._renderButtonItem(s).appendTo(this.button),this.options.width!==!1&&this._resizeButton(),this._on(this.button,this._buttonEvents),this.button.one("focusin",function(){i._rendered||i._refreshMenu()})},_drawMenu:function(){var e=this;this.menu=t("<ul>",{"aria-hidden":"true","aria-labelledby":this.ids.button,id:this.ids.menu}),this.menuWrap=t("<div>").append(this.menu),this._addClass(this.menuWrap,"ui-selectmenu-menu","ui-front"),this.menuWrap.appendTo(this._appendTo()),this.menuInstance=this.menu.menu({classes:{"ui-menu":"ui-corner-bottom"},role:"listbox",select:function(t,i){t.preventDefault(),e._setSelection(),e._select(i.item.data("ui-selectmenu-item"),t)},focus:function(t,i){var s=i.item.data("ui-selectmenu-item");null!=e.focusIndex&&s.index!==e.focusIndex&&(e._trigger("focus",t,{item:s}),e.isOpen||e._select(s,t)),e.focusIndex=s.index,e.button.attr("aria-activedescendant",e.menuItems.eq(s.index).attr("id"))}}).menu("instance"),this.menuInstance._off(this.menu,"mouseleave"),this.menuInstance._closeOnDocumentClick=function(){return!1},this.menuInstance._isDivider=function(){return!1}},refresh:function(){this._refreshMenu(),this.buttonItem.replaceWith(this.buttonItem=this._renderButtonItem(this._getSelectedItem().data("ui-selectmenu-item")||{})),null===this.options.width&&this._resizeButton()},_refreshMenu:function(){var t,e=this.element.find("option");this.menu.empty(),this._parseOptions(e),this._renderMenu(this.menu,this.items),this.menuInstance.refresh(),this.menuItems=this.menu.find("li").not(".ui-selectmenu-optgroup").find(".ui-menu-item-wrapper"),this._rendered=!0,e.length&&(t=this._getSelectedItem(),this.menuInstance.focus(null,t),this._setAria(t.data("ui-selectmenu-item")),this._setOption("disabled",this.element.prop("disabled")))},open:function(t){this.options.disabled||(this._rendered?(this._removeClass(this.menu.find(".ui-state-active"),null,"ui-state-active"),this.menuInstance.focus(null,this._getSelectedItem())):this._refreshMenu(),this.menuItems.length&&(this.isOpen=!0,this._toggleAttr(),this._resizeMenu(),this._position(),this._on(this.document,this._documentClick),this._trigger("open",t)))},_position:function(){this.menuWrap.position(t.extend({of:this.button},this.options.position))},close:function(t){this.isOpen&&(this.isOpen=!1,this._toggleAttr(),this.range=null,this._off(this.document),this._trigger("close",t))},widget:function(){return this.button},menuWidget:function(){return this.menu},_renderButtonItem:function(e){var i=t("<span>");return this._setText(i,e.label),this._addClass(i,"ui-selectmenu-text"),i},_renderMenu:function(e,i){var s=this,n="";t.each(i,function(i,o){var a;o.optgroup!==n&&(a=t("<li>",{text:o.optgroup}),s._addClass(a,"ui-selectmenu-optgroup","ui-menu-divider"+(o.element.parent("optgroup").prop("disabled")?" ui-state-disabled":"")),a.appendTo(e),n=o.optgroup),s._renderItemData(e,o)})},_renderItemData:function(t,e){return this._renderItem(t,e).data("ui-selectmenu-item",e)},_renderItem:function(e,i){var s=t("<li>"),n=t("<div>",{title:i.element.attr("title")});return i.disabled&&this._addClass(s,null,"ui-state-disabled"),this._setText(n,i.label),s.append(n).appendTo(e)},_setText:function(t,e){e?t.text(e):t.html("&#160;")},_move:function(t,e){var i,s,n=".ui-menu-item";this.isOpen?i=this.menuItems.eq(this.focusIndex).parent("li"):(i=this.menuItems.eq(this.element[0].selectedIndex).parent("li"),n+=":not(.ui-state-disabled)"),s="first"===t||"last"===t?i["first"===t?"prevAll":"nextAll"](n).eq(-1):i[t+"All"](n).eq(0),s.length&&this.menuInstance.focus(e,s)},_getSelectedItem:function(){return this.menuItems.eq(this.element[0].selectedIndex).parent("li")},_toggle:function(t){this[this.isOpen?"close":"open"](t)},_setSelection:function(){var t;this.range&&(window.getSelection?(t=window.getSelection(),t.removeAllRanges(),t.addRange(this.range)):this.range.select(),this.button.focus())},_documentClick:{mousedown:function(e){this.isOpen&&(t(e.target).closest(".ui-selectmenu-menu, #"+t.ui.escapeSelector(this.ids.button)).length||this.close(e))}},_buttonEvents:{mousedown:function(){var t;window.getSelection?(t=window.getSelection(),t.rangeCount&&(this.range=t.getRangeAt(0))):this.range=document.selection.createRange()},click:function(t){this._setSelection(),this._toggle(t)},keydown:function(e){var i=!0;switch(e.keyCode){case t.ui.keyCode.TAB:case t.ui.keyCode.ESCAPE:this.close(e),i=!1;break;case t.ui.keyCode.ENTER:this.isOpen&&this._selectFocusedItem(e);break;case t.ui.keyCode.UP:e.altKey?this._toggle(e):this._move("prev",e);break;case t.ui.keyCode.DOWN:e.altKey?this._toggle(e):this._move("next",e);break;case t.ui.keyCode.SPACE:this.isOpen?this._selectFocusedItem(e):this._toggle(e);break;case t.ui.keyCode.LEFT:this._move("prev",e);break;case t.ui.keyCode.RIGHT:this._move("next",e);break;case t.ui.keyCode.HOME:case t.ui.keyCode.PAGE_UP:this._move("first",e);break;case t.ui.keyCode.END:case t.ui.keyCode.PAGE_DOWN:this._move("last",e);break;default:this.menu.trigger(e),i=!1}i&&e.preventDefault()}},_selectFocusedItem:function(t){var e=this.menuItems.eq(this.focusIndex).parent("li");e.hasClass("ui-state-disabled")||this._select(e.data("ui-selectmenu-item"),t)},_select:function(t,e){var i=this.element[0].selectedIndex;this.element[0].selectedIndex=t.index,this.buttonItem.replaceWith(this.buttonItem=this._renderButtonItem(t)),this._setAria(t),this._trigger("select",e,{item:t}),t.index!==i&&this._trigger("change",e,{item:t}),this.close(e)},_setAria:function(t){var e=this.menuItems.eq(t.index).attr("id");this.button.attr({"aria-labelledby":e,"aria-activedescendant":e}),this.menu.attr("aria-activedescendant",e)},_setOption:function(t,e){if("icons"===t){var i=this.button.find("span.ui-icon");this._removeClass(i,null,this.options.icons.button)._addClass(i,null,e.button)}this._super(t,e),"appendTo"===t&&this.menuWrap.appendTo(this._appendTo()),"width"===t&&this._resizeButton()},_setOptionDisabled:function(t){this._super(t),this.menuInstance.option("disabled",t),this.button.attr("aria-disabled",t),this._toggleClass(this.button,null,"ui-state-disabled",t),this.element.prop("disabled",t),t?(this.button.attr("tabindex",-1),this.close()):this.button.attr("tabindex",0)},_appendTo:function(){var e=this.options.appendTo;return e&&(e=e.jquery||e.nodeType?t(e):this.document.find(e).eq(0)),e&&e[0]||(e=this.element.closest(".ui-front, dialog")),e.length||(e=this.document[0].body),e},_toggleAttr:function(){this.button.attr("aria-expanded",this.isOpen),this._removeClass(this.button,"ui-selectmenu-button-"+(this.isOpen?"closed":"open"))._addClass(this.button,"ui-selectmenu-button-"+(this.isOpen?"open":"closed"))._toggleClass(this.menuWrap,"ui-selectmenu-open",null,this.isOpen),this.menu.attr("aria-hidden",!this.isOpen)},_resizeButton:function(){var t=this.options.width;return t===!1?(this.button.css("width",""),void 0):(null===t&&(t=this.element.show().outerWidth(),this.element.hide()),this.button.outerWidth(t),void 0)},_resizeMenu:function(){this.menu.outerWidth(Math.max(this.button.outerWidth(),this.menu.width("").outerWidth()+1))},_getCreateOptions:function(){var t=this._super();return t.disabled=this.element.prop("disabled"),t},_parseOptions:function(e){var i=this,s=[];e.each(function(e,n){s.push(i._parseOption(t(n),e))}),this.items=s},_parseOption:function(t,e){var i=t.parent("optgroup");return{element:t,index:e,value:t.val(),label:t.text(),optgroup:i.attr("label")||"",disabled:i.prop("disabled")||t.prop("disabled")}},_destroy:function(){this._unbindFormResetHandler(),this.menuWrap.remove(),this.button.remove(),this.element.show(),this.element.removeUniqueId(),this.labels.attr("for",this.ids.element)}}]),t.widget("ui.slider",t.ui.mouse,{version:"1.12.1",widgetEventPrefix:"slide",options:{animate:!1,classes:{"ui-slider":"ui-corner-all","ui-slider-handle":"ui-corner-all","ui-slider-range":"ui-corner-all ui-widget-header"},distance:0,max:100,min:0,orientation:"horizontal",range:!1,step:1,value:0,values:null,change:null,slide:null,start:null,stop:null},numPages:5,_create:function(){this._keySliding=!1,this._mouseSliding=!1,this._animateOff=!0,this._handleIndex=null,this._detectOrientation(),this._mouseInit(),this._calculateNewMax(),this._addClass("ui-slider ui-slider-"+this.orientation,"ui-widget ui-widget-content"),this._refresh(),this._animateOff=!1
},_refresh:function(){this._createRange(),this._createHandles(),this._setupEvents(),this._refreshValue()},_createHandles:function(){var e,i,s=this.options,n=this.element.find(".ui-slider-handle"),o="<span tabindex='0'></span>",a=[];for(i=s.values&&s.values.length||1,n.length>i&&(n.slice(i).remove(),n=n.slice(0,i)),e=n.length;i>e;e++)a.push(o);this.handles=n.add(t(a.join("")).appendTo(this.element)),this._addClass(this.handles,"ui-slider-handle","ui-state-default"),this.handle=this.handles.eq(0),this.handles.each(function(e){t(this).data("ui-slider-handle-index",e).attr("tabIndex",0)})},_createRange:function(){var e=this.options;e.range?(e.range===!0&&(e.values?e.values.length&&2!==e.values.length?e.values=[e.values[0],e.values[0]]:t.isArray(e.values)&&(e.values=e.values.slice(0)):e.values=[this._valueMin(),this._valueMin()]),this.range&&this.range.length?(this._removeClass(this.range,"ui-slider-range-min ui-slider-range-max"),this.range.css({left:"",bottom:""})):(this.range=t("<div>").appendTo(this.element),this._addClass(this.range,"ui-slider-range")),("min"===e.range||"max"===e.range)&&this._addClass(this.range,"ui-slider-range-"+e.range)):(this.range&&this.range.remove(),this.range=null)},_setupEvents:function(){this._off(this.handles),this._on(this.handles,this._handleEvents),this._hoverable(this.handles),this._focusable(this.handles)},_destroy:function(){this.handles.remove(),this.range&&this.range.remove(),this._mouseDestroy()},_mouseCapture:function(e){var i,s,n,o,a,r,h,l,c=this,u=this.options;return u.disabled?!1:(this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()},this.elementOffset=this.element.offset(),i={x:e.pageX,y:e.pageY},s=this._normValueFromMouse(i),n=this._valueMax()-this._valueMin()+1,this.handles.each(function(e){var i=Math.abs(s-c.values(e));(n>i||n===i&&(e===c._lastChangedValue||c.values(e)===u.min))&&(n=i,o=t(this),a=e)}),r=this._start(e,a),r===!1?!1:(this._mouseSliding=!0,this._handleIndex=a,this._addClass(o,null,"ui-state-active"),o.trigger("focus"),h=o.offset(),l=!t(e.target).parents().addBack().is(".ui-slider-handle"),this._clickOffset=l?{left:0,top:0}:{left:e.pageX-h.left-o.width()/2,top:e.pageY-h.top-o.height()/2-(parseInt(o.css("borderTopWidth"),10)||0)-(parseInt(o.css("borderBottomWidth"),10)||0)+(parseInt(o.css("marginTop"),10)||0)},this.handles.hasClass("ui-state-hover")||this._slide(e,a,s),this._animateOff=!0,!0))},_mouseStart:function(){return!0},_mouseDrag:function(t){var e={x:t.pageX,y:t.pageY},i=this._normValueFromMouse(e);return this._slide(t,this._handleIndex,i),!1},_mouseStop:function(t){return this._removeClass(this.handles,null,"ui-state-active"),this._mouseSliding=!1,this._stop(t,this._handleIndex),this._change(t,this._handleIndex),this._handleIndex=null,this._clickOffset=null,this._animateOff=!1,!1},_detectOrientation:function(){this.orientation="vertical"===this.options.orientation?"vertical":"horizontal"},_normValueFromMouse:function(t){var e,i,s,n,o;return"horizontal"===this.orientation?(e=this.elementSize.width,i=t.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)):(e=this.elementSize.height,i=t.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)),s=i/e,s>1&&(s=1),0>s&&(s=0),"vertical"===this.orientation&&(s=1-s),n=this._valueMax()-this._valueMin(),o=this._valueMin()+s*n,this._trimAlignValue(o)},_uiHash:function(t,e,i){var s={handle:this.handles[t],handleIndex:t,value:void 0!==e?e:this.value()};return this._hasMultipleValues()&&(s.value=void 0!==e?e:this.values(t),s.values=i||this.values()),s},_hasMultipleValues:function(){return this.options.values&&this.options.values.length},_start:function(t,e){return this._trigger("start",t,this._uiHash(e))},_slide:function(t,e,i){var s,n,o=this.value(),a=this.values();this._hasMultipleValues()&&(n=this.values(e?0:1),o=this.values(e),2===this.options.values.length&&this.options.range===!0&&(i=0===e?Math.min(n,i):Math.max(n,i)),a[e]=i),i!==o&&(s=this._trigger("slide",t,this._uiHash(e,i,a)),s!==!1&&(this._hasMultipleValues()?this.values(e,i):this.value(i)))},_stop:function(t,e){this._trigger("stop",t,this._uiHash(e))},_change:function(t,e){this._keySliding||this._mouseSliding||(this._lastChangedValue=e,this._trigger("change",t,this._uiHash(e)))},value:function(t){return arguments.length?(this.options.value=this._trimAlignValue(t),this._refreshValue(),this._change(null,0),void 0):this._value()},values:function(e,i){var s,n,o;if(arguments.length>1)return this.options.values[e]=this._trimAlignValue(i),this._refreshValue(),this._change(null,e),void 0;if(!arguments.length)return this._values();if(!t.isArray(arguments[0]))return this._hasMultipleValues()?this._values(e):this.value();for(s=this.options.values,n=arguments[0],o=0;s.length>o;o+=1)s[o]=this._trimAlignValue(n[o]),this._change(null,o);this._refreshValue()},_setOption:function(e,i){var s,n=0;switch("range"===e&&this.options.range===!0&&("min"===i?(this.options.value=this._values(0),this.options.values=null):"max"===i&&(this.options.value=this._values(this.options.values.length-1),this.options.values=null)),t.isArray(this.options.values)&&(n=this.options.values.length),this._super(e,i),e){case"orientation":this._detectOrientation(),this._removeClass("ui-slider-horizontal ui-slider-vertical")._addClass("ui-slider-"+this.orientation),this._refreshValue(),this.options.range&&this._refreshRange(i),this.handles.css("horizontal"===i?"bottom":"left","");break;case"value":this._animateOff=!0,this._refreshValue(),this._change(null,0),this._animateOff=!1;break;case"values":for(this._animateOff=!0,this._refreshValue(),s=n-1;s>=0;s--)this._change(null,s);this._animateOff=!1;break;case"step":case"min":case"max":this._animateOff=!0,this._calculateNewMax(),this._refreshValue(),this._animateOff=!1;break;case"range":this._animateOff=!0,this._refresh(),this._animateOff=!1}},_setOptionDisabled:function(t){this._super(t),this._toggleClass(null,"ui-state-disabled",!!t)},_value:function(){var t=this.options.value;return t=this._trimAlignValue(t)},_values:function(t){var e,i,s;if(arguments.length)return e=this.options.values[t],e=this._trimAlignValue(e);if(this._hasMultipleValues()){for(i=this.options.values.slice(),s=0;i.length>s;s+=1)i[s]=this._trimAlignValue(i[s]);return i}return[]},_trimAlignValue:function(t){if(this._valueMin()>=t)return this._valueMin();if(t>=this._valueMax())return this._valueMax();var e=this.options.step>0?this.options.step:1,i=(t-this._valueMin())%e,s=t-i;return 2*Math.abs(i)>=e&&(s+=i>0?e:-e),parseFloat(s.toFixed(5))},_calculateNewMax:function(){var t=this.options.max,e=this._valueMin(),i=this.options.step,s=Math.round((t-e)/i)*i;t=s+e,t>this.options.max&&(t-=i),this.max=parseFloat(t.toFixed(this._precision()))},_precision:function(){var t=this._precisionOf(this.options.step);return null!==this.options.min&&(t=Math.max(t,this._precisionOf(this.options.min))),t},_precisionOf:function(t){var e=""+t,i=e.indexOf(".");return-1===i?0:e.length-i-1},_valueMin:function(){return this.options.min},_valueMax:function(){return this.max},_refreshRange:function(t){"vertical"===t&&this.range.css({width:"",left:""}),"horizontal"===t&&this.range.css({height:"",bottom:""})},_refreshValue:function(){var e,i,s,n,o,a=this.options.range,r=this.options,h=this,l=this._animateOff?!1:r.animate,c={};this._hasMultipleValues()?this.handles.each(function(s){i=100*((h.values(s)-h._valueMin())/(h._valueMax()-h._valueMin())),c["horizontal"===h.orientation?"left":"bottom"]=i+"%",t(this).stop(1,1)[l?"animate":"css"](c,r.animate),h.options.range===!0&&("horizontal"===h.orientation?(0===s&&h.range.stop(1,1)[l?"animate":"css"]({left:i+"%"},r.animate),1===s&&h.range[l?"animate":"css"]({width:i-e+"%"},{queue:!1,duration:r.animate})):(0===s&&h.range.stop(1,1)[l?"animate":"css"]({bottom:i+"%"},r.animate),1===s&&h.range[l?"animate":"css"]({height:i-e+"%"},{queue:!1,duration:r.animate}))),e=i}):(s=this.value(),n=this._valueMin(),o=this._valueMax(),i=o!==n?100*((s-n)/(o-n)):0,c["horizontal"===this.orientation?"left":"bottom"]=i+"%",this.handle.stop(1,1)[l?"animate":"css"](c,r.animate),"min"===a&&"horizontal"===this.orientation&&this.range.stop(1,1)[l?"animate":"css"]({width:i+"%"},r.animate),"max"===a&&"horizontal"===this.orientation&&this.range.stop(1,1)[l?"animate":"css"]({width:100-i+"%"},r.animate),"min"===a&&"vertical"===this.orientation&&this.range.stop(1,1)[l?"animate":"css"]({height:i+"%"},r.animate),"max"===a&&"vertical"===this.orientation&&this.range.stop(1,1)[l?"animate":"css"]({height:100-i+"%"},r.animate))},_handleEvents:{keydown:function(e){var i,s,n,o,a=t(e.target).data("ui-slider-handle-index");switch(e.keyCode){case t.ui.keyCode.HOME:case t.ui.keyCode.END:case t.ui.keyCode.PAGE_UP:case t.ui.keyCode.PAGE_DOWN:case t.ui.keyCode.UP:case t.ui.keyCode.RIGHT:case t.ui.keyCode.DOWN:case t.ui.keyCode.LEFT:if(e.preventDefault(),!this._keySliding&&(this._keySliding=!0,this._addClass(t(e.target),null,"ui-state-active"),i=this._start(e,a),i===!1))return}switch(o=this.options.step,s=n=this._hasMultipleValues()?this.values(a):this.value(),e.keyCode){case t.ui.keyCode.HOME:n=this._valueMin();break;case t.ui.keyCode.END:n=this._valueMax();break;case t.ui.keyCode.PAGE_UP:n=this._trimAlignValue(s+(this._valueMax()-this._valueMin())/this.numPages);break;case t.ui.keyCode.PAGE_DOWN:n=this._trimAlignValue(s-(this._valueMax()-this._valueMin())/this.numPages);break;case t.ui.keyCode.UP:case t.ui.keyCode.RIGHT:if(s===this._valueMax())return;n=this._trimAlignValue(s+o);break;case t.ui.keyCode.DOWN:case t.ui.keyCode.LEFT:if(s===this._valueMin())return;n=this._trimAlignValue(s-o)}this._slide(e,a,n)},keyup:function(e){var i=t(e.target).data("ui-slider-handle-index");this._keySliding&&(this._keySliding=!1,this._stop(e,i),this._change(e,i),this._removeClass(t(e.target),null,"ui-state-active"))}}}),t.widget("ui.sortable",t.ui.mouse,{version:"1.12.1",widgetEventPrefix:"sort",ready:!1,options:{appendTo:"parent",axis:!1,connectWith:!1,containment:!1,cursor:"auto",cursorAt:!1,dropOnEmpty:!0,forcePlaceholderSize:!1,forceHelperSize:!1,grid:!1,handle:!1,helper:"original",items:"> *",opacity:!1,placeholder:!1,revert:!1,scroll:!0,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1e3,activate:null,beforeStop:null,change:null,deactivate:null,out:null,over:null,receive:null,remove:null,sort:null,start:null,stop:null,update:null},_isOverAxis:function(t,e,i){return t>=e&&e+i>t},_isFloating:function(t){return/left|right/.test(t.css("float"))||/inline|table-cell/.test(t.css("display"))},_create:function(){this.containerCache={},this._addClass("ui-sortable"),this.refresh(),this.offset=this.element.offset(),this._mouseInit(),this._setHandleClassName(),this.ready=!0},_setOption:function(t,e){this._super(t,e),"handle"===t&&this._setHandleClassName()},_setHandleClassName:function(){var e=this;this._removeClass(this.element.find(".ui-sortable-handle"),"ui-sortable-handle"),t.each(this.items,function(){e._addClass(this.instance.options.handle?this.item.find(this.instance.options.handle):this.item,"ui-sortable-handle")})},_destroy:function(){this._mouseDestroy();for(var t=this.items.length-1;t>=0;t--)this.items[t].item.removeData(this.widgetName+"-item");return this},_mouseCapture:function(e,i){var s=null,n=!1,o=this;return this.reverting?!1:this.options.disabled||"static"===this.options.type?!1:(this._refreshItems(e),t(e.target).parents().each(function(){return t.data(this,o.widgetName+"-item")===o?(s=t(this),!1):void 0}),t.data(e.target,o.widgetName+"-item")===o&&(s=t(e.target)),s?!this.options.handle||i||(t(this.options.handle,s).find("*").addBack().each(function(){this===e.target&&(n=!0)}),n)?(this.currentItem=s,this._removeCurrentsFromItems(),!0):!1:!1)},_mouseStart:function(e,i,s){var n,o,a=this.options;if(this.currentContainer=this,this.refreshPositions(),this.helper=this._createHelper(e),this._cacheHelperProportions(),this._cacheMargins(),this.scrollParent=this.helper.scrollParent(),this.offset=this.currentItem.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},t.extend(this.offset,{click:{left:e.pageX-this.offset.left,top:e.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.helper.css("position","absolute"),this.cssPosition=this.helper.css("position"),this.originalPosition=this._generatePosition(e),this.originalPageX=e.pageX,this.originalPageY=e.pageY,a.cursorAt&&this._adjustOffsetFromHelper(a.cursorAt),this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]},this.helper[0]!==this.currentItem[0]&&this.currentItem.hide(),this._createPlaceholder(),a.containment&&this._setContainment(),a.cursor&&"auto"!==a.cursor&&(o=this.document.find("body"),this.storedCursor=o.css("cursor"),o.css("cursor",a.cursor),this.storedStylesheet=t("<style>*{ cursor: "+a.cursor+" !important; }</style>").appendTo(o)),a.opacity&&(this.helper.css("opacity")&&(this._storedOpacity=this.helper.css("opacity")),this.helper.css("opacity",a.opacity)),a.zIndex&&(this.helper.css("zIndex")&&(this._storedZIndex=this.helper.css("zIndex")),this.helper.css("zIndex",a.zIndex)),this.scrollParent[0]!==this.document[0]&&"HTML"!==this.scrollParent[0].tagName&&(this.overflowOffset=this.scrollParent.offset()),this._trigger("start",e,this._uiHash()),this._preserveHelperProportions||this._cacheHelperProportions(),!s)for(n=this.containers.length-1;n>=0;n--)this.containers[n]._trigger("activate",e,this._uiHash(this));return t.ui.ddmanager&&(t.ui.ddmanager.current=this),t.ui.ddmanager&&!a.dropBehaviour&&t.ui.ddmanager.prepareOffsets(this,e),this.dragging=!0,this._addClass(this.helper,"ui-sortable-helper"),this._mouseDrag(e),!0},_mouseDrag:function(e){var i,s,n,o,a=this.options,r=!1;for(this.position=this._generatePosition(e),this.positionAbs=this._convertPositionTo("absolute"),this.lastPositionAbs||(this.lastPositionAbs=this.positionAbs),this.options.scroll&&(this.scrollParent[0]!==this.document[0]&&"HTML"!==this.scrollParent[0].tagName?(this.overflowOffset.top+this.scrollParent[0].offsetHeight-e.pageY<a.scrollSensitivity?this.scrollParent[0].scrollTop=r=this.scrollParent[0].scrollTop+a.scrollSpeed:e.pageY-this.overflowOffset.top<a.scrollSensitivity&&(this.scrollParent[0].scrollTop=r=this.scrollParent[0].scrollTop-a.scrollSpeed),this.overflowOffset.left+this.scrollParent[0].offsetWidth-e.pageX<a.scrollSensitivity?this.scrollParent[0].scrollLeft=r=this.scrollParent[0].scrollLeft+a.scrollSpeed:e.pageX-this.overflowOffset.left<a.scrollSensitivity&&(this.scrollParent[0].scrollLeft=r=this.scrollParent[0].scrollLeft-a.scrollSpeed)):(e.pageY-this.document.scrollTop()<a.scrollSensitivity?r=this.document.scrollTop(this.document.scrollTop()-a.scrollSpeed):this.window.height()-(e.pageY-this.document.scrollTop())<a.scrollSensitivity&&(r=this.document.scrollTop(this.document.scrollTop()+a.scrollSpeed)),e.pageX-this.document.scrollLeft()<a.scrollSensitivity?r=this.document.scrollLeft(this.document.scrollLeft()-a.scrollSpeed):this.window.width()-(e.pageX-this.document.scrollLeft())<a.scrollSensitivity&&(r=this.document.scrollLeft(this.document.scrollLeft()+a.scrollSpeed))),r!==!1&&t.ui.ddmanager&&!a.dropBehaviour&&t.ui.ddmanager.prepareOffsets(this,e)),this.positionAbs=this._convertPositionTo("absolute"),this.options.axis&&"y"===this.options.axis||(this.helper[0].style.left=this.position.left+"px"),this.options.axis&&"x"===this.options.axis||(this.helper[0].style.top=this.position.top+"px"),i=this.items.length-1;i>=0;i--)if(s=this.items[i],n=s.item[0],o=this._intersectsWithPointer(s),o&&s.instance===this.currentContainer&&n!==this.currentItem[0]&&this.placeholder[1===o?"next":"prev"]()[0]!==n&&!t.contains(this.placeholder[0],n)&&("semi-dynamic"===this.options.type?!t.contains(this.element[0],n):!0)){if(this.direction=1===o?"down":"up","pointer"!==this.options.tolerance&&!this._intersectsWithSides(s))break;this._rearrange(e,s),this._trigger("change",e,this._uiHash());break}return this._contactContainers(e),t.ui.ddmanager&&t.ui.ddmanager.drag(this,e),this._trigger("sort",e,this._uiHash()),this.lastPositionAbs=this.positionAbs,!1},_mouseStop:function(e,i){if(e){if(t.ui.ddmanager&&!this.options.dropBehaviour&&t.ui.ddmanager.drop(this,e),this.options.revert){var s=this,n=this.placeholder.offset(),o=this.options.axis,a={};o&&"x"!==o||(a.left=n.left-this.offset.parent.left-this.margins.left+(this.offsetParent[0]===this.document[0].body?0:this.offsetParent[0].scrollLeft)),o&&"y"!==o||(a.top=n.top-this.offset.parent.top-this.margins.top+(this.offsetParent[0]===this.document[0].body?0:this.offsetParent[0].scrollTop)),this.reverting=!0,t(this.helper).animate(a,parseInt(this.options.revert,10)||500,function(){s._clear(e)})}else this._clear(e,i);return!1}},cancel:function(){if(this.dragging){this._mouseUp(new t.Event("mouseup",{target:null})),"original"===this.options.helper?(this.currentItem.css(this._storedCSS),this._removeClass(this.currentItem,"ui-sortable-helper")):this.currentItem.show();for(var e=this.containers.length-1;e>=0;e--)this.containers[e]._trigger("deactivate",null,this._uiHash(this)),this.containers[e].containerCache.over&&(this.containers[e]._trigger("out",null,this._uiHash(this)),this.containers[e].containerCache.over=0)}return this.placeholder&&(this.placeholder[0].parentNode&&this.placeholder[0].parentNode.removeChild(this.placeholder[0]),"original"!==this.options.helper&&this.helper&&this.helper[0].parentNode&&this.helper.remove(),t.extend(this,{helper:null,dragging:!1,reverting:!1,_noFinalSort:null}),this.domPosition.prev?t(this.domPosition.prev).after(this.currentItem):t(this.domPosition.parent).prepend(this.currentItem)),this},serialize:function(e){var i=this._getItemsAsjQuery(e&&e.connected),s=[];return e=e||{},t(i).each(function(){var i=(t(e.item||this).attr(e.attribute||"id")||"").match(e.expression||/(.+)[\-=_](.+)/);i&&s.push((e.key||i[1]+"[]")+"="+(e.key&&e.expression?i[1]:i[2]))}),!s.length&&e.key&&s.push(e.key+"="),s.join("&")},toArray:function(e){var i=this._getItemsAsjQuery(e&&e.connected),s=[];return e=e||{},i.each(function(){s.push(t(e.item||this).attr(e.attribute||"id")||"")}),s},_intersectsWith:function(t){var e=this.positionAbs.left,i=e+this.helperProportions.width,s=this.positionAbs.top,n=s+this.helperProportions.height,o=t.left,a=o+t.width,r=t.top,h=r+t.height,l=this.offset.click.top,c=this.offset.click.left,u="x"===this.options.axis||s+l>r&&h>s+l,d="y"===this.options.axis||e+c>o&&a>e+c,p=u&&d;return"pointer"===this.options.tolerance||this.options.forcePointerForContainers||"pointer"!==this.options.tolerance&&this.helperProportions[this.floating?"width":"height"]>t[this.floating?"width":"height"]?p:e+this.helperProportions.width/2>o&&a>i-this.helperProportions.width/2&&s+this.helperProportions.height/2>r&&h>n-this.helperProportions.height/2},_intersectsWithPointer:function(t){var e,i,s="x"===this.options.axis||this._isOverAxis(this.positionAbs.top+this.offset.click.top,t.top,t.height),n="y"===this.options.axis||this._isOverAxis(this.positionAbs.left+this.offset.click.left,t.left,t.width),o=s&&n;return o?(e=this._getDragVerticalDirection(),i=this._getDragHorizontalDirection(),this.floating?"right"===i||"down"===e?2:1:e&&("down"===e?2:1)):!1},_intersectsWithSides:function(t){var e=this._isOverAxis(this.positionAbs.top+this.offset.click.top,t.top+t.height/2,t.height),i=this._isOverAxis(this.positionAbs.left+this.offset.click.left,t.left+t.width/2,t.width),s=this._getDragVerticalDirection(),n=this._getDragHorizontalDirection();return this.floating&&n?"right"===n&&i||"left"===n&&!i:s&&("down"===s&&e||"up"===s&&!e)},_getDragVerticalDirection:function(){var t=this.positionAbs.top-this.lastPositionAbs.top;return 0!==t&&(t>0?"down":"up")},_getDragHorizontalDirection:function(){var t=this.positionAbs.left-this.lastPositionAbs.left;return 0!==t&&(t>0?"right":"left")},refresh:function(t){return this._refreshItems(t),this._setHandleClassName(),this.refreshPositions(),this},_connectWith:function(){var t=this.options;return t.connectWith.constructor===String?[t.connectWith]:t.connectWith},_getItemsAsjQuery:function(e){function i(){r.push(this)}var s,n,o,a,r=[],h=[],l=this._connectWith();if(l&&e)for(s=l.length-1;s>=0;s--)for(o=t(l[s],this.document[0]),n=o.length-1;n>=0;n--)a=t.data(o[n],this.widgetFullName),a&&a!==this&&!a.options.disabled&&h.push([t.isFunction(a.options.items)?a.options.items.call(a.element):t(a.options.items,a.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),a]);for(h.push([t.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):t(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]),s=h.length-1;s>=0;s--)h[s][0].each(i);return t(r)},_removeCurrentsFromItems:function(){var e=this.currentItem.find(":data("+this.widgetName+"-item)");this.items=t.grep(this.items,function(t){for(var i=0;e.length>i;i++)if(e[i]===t.item[0])return!1;return!0})},_refreshItems:function(e){this.items=[],this.containers=[this];var i,s,n,o,a,r,h,l,c=this.items,u=[[t.isFunction(this.options.items)?this.options.items.call(this.element[0],e,{item:this.currentItem}):t(this.options.items,this.element),this]],d=this._connectWith();if(d&&this.ready)for(i=d.length-1;i>=0;i--)for(n=t(d[i],this.document[0]),s=n.length-1;s>=0;s--)o=t.data(n[s],this.widgetFullName),o&&o!==this&&!o.options.disabled&&(u.push([t.isFunction(o.options.items)?o.options.items.call(o.element[0],e,{item:this.currentItem}):t(o.options.items,o.element),o]),this.containers.push(o));for(i=u.length-1;i>=0;i--)for(a=u[i][1],r=u[i][0],s=0,l=r.length;l>s;s++)h=t(r[s]),h.data(this.widgetName+"-item",a),c.push({item:h,instance:a,width:0,height:0,left:0,top:0})},refreshPositions:function(e){this.floating=this.items.length?"x"===this.options.axis||this._isFloating(this.items[0].item):!1,this.offsetParent&&this.helper&&(this.offset.parent=this._getParentOffset());var i,s,n,o;for(i=this.items.length-1;i>=0;i--)s=this.items[i],s.instance!==this.currentContainer&&this.currentContainer&&s.item[0]!==this.currentItem[0]||(n=this.options.toleranceElement?t(this.options.toleranceElement,s.item):s.item,e||(s.width=n.outerWidth(),s.height=n.outerHeight()),o=n.offset(),s.left=o.left,s.top=o.top);if(this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(i=this.containers.length-1;i>=0;i--)o=this.containers[i].element.offset(),this.containers[i].containerCache.left=o.left,this.containers[i].containerCache.top=o.top,this.containers[i].containerCache.width=this.containers[i].element.outerWidth(),this.containers[i].containerCache.height=this.containers[i].element.outerHeight();return this},_createPlaceholder:function(e){e=e||this;var i,s=e.options;s.placeholder&&s.placeholder.constructor!==String||(i=s.placeholder,s.placeholder={element:function(){var s=e.currentItem[0].nodeName.toLowerCase(),n=t("<"+s+">",e.document[0]);return e._addClass(n,"ui-sortable-placeholder",i||e.currentItem[0].className)._removeClass(n,"ui-sortable-helper"),"tbody"===s?e._createTrPlaceholder(e.currentItem.find("tr").eq(0),t("<tr>",e.document[0]).appendTo(n)):"tr"===s?e._createTrPlaceholder(e.currentItem,n):"img"===s&&n.attr("src",e.currentItem.attr("src")),i||n.css("visibility","hidden"),n},update:function(t,n){(!i||s.forcePlaceholderSize)&&(n.height()||n.height(e.currentItem.innerHeight()-parseInt(e.currentItem.css("paddingTop")||0,10)-parseInt(e.currentItem.css("paddingBottom")||0,10)),n.width()||n.width(e.currentItem.innerWidth()-parseInt(e.currentItem.css("paddingLeft")||0,10)-parseInt(e.currentItem.css("paddingRight")||0,10)))}}),e.placeholder=t(s.placeholder.element.call(e.element,e.currentItem)),e.currentItem.after(e.placeholder),s.placeholder.update(e,e.placeholder)},_createTrPlaceholder:function(e,i){var s=this;e.children().each(function(){t("<td>&#160;</td>",s.document[0]).attr("colspan",t(this).attr("colspan")||1).appendTo(i)})},_contactContainers:function(e){var i,s,n,o,a,r,h,l,c,u,d=null,p=null;for(i=this.containers.length-1;i>=0;i--)if(!t.contains(this.currentItem[0],this.containers[i].element[0]))if(this._intersectsWith(this.containers[i].containerCache)){if(d&&t.contains(this.containers[i].element[0],d.element[0]))continue;d=this.containers[i],p=i}else this.containers[i].containerCache.over&&(this.containers[i]._trigger("out",e,this._uiHash(this)),this.containers[i].containerCache.over=0);if(d)if(1===this.containers.length)this.containers[p].containerCache.over||(this.containers[p]._trigger("over",e,this._uiHash(this)),this.containers[p].containerCache.over=1);else{for(n=1e4,o=null,c=d.floating||this._isFloating(this.currentItem),a=c?"left":"top",r=c?"width":"height",u=c?"pageX":"pageY",s=this.items.length-1;s>=0;s--)t.contains(this.containers[p].element[0],this.items[s].item[0])&&this.items[s].item[0]!==this.currentItem[0]&&(h=this.items[s].item.offset()[a],l=!1,e[u]-h>this.items[s][r]/2&&(l=!0),n>Math.abs(e[u]-h)&&(n=Math.abs(e[u]-h),o=this.items[s],this.direction=l?"up":"down"));if(!o&&!this.options.dropOnEmpty)return;if(this.currentContainer===this.containers[p])return this.currentContainer.containerCache.over||(this.containers[p]._trigger("over",e,this._uiHash()),this.currentContainer.containerCache.over=1),void 0;o?this._rearrange(e,o,null,!0):this._rearrange(e,null,this.containers[p].element,!0),this._trigger("change",e,this._uiHash()),this.containers[p]._trigger("change",e,this._uiHash(this)),this.currentContainer=this.containers[p],this.options.placeholder.update(this.currentContainer,this.placeholder),this.containers[p]._trigger("over",e,this._uiHash(this)),this.containers[p].containerCache.over=1}},_createHelper:function(e){var i=this.options,s=t.isFunction(i.helper)?t(i.helper.apply(this.element[0],[e,this.currentItem])):"clone"===i.helper?this.currentItem.clone():this.currentItem;return s.parents("body").length||t("parent"!==i.appendTo?i.appendTo:this.currentItem[0].parentNode)[0].appendChild(s[0]),s[0]===this.currentItem[0]&&(this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")}),(!s[0].style.width||i.forceHelperSize)&&s.width(this.currentItem.width()),(!s[0].style.height||i.forceHelperSize)&&s.height(this.currentItem.height()),s},_adjustOffsetFromHelper:function(e){"string"==typeof e&&(e=e.split(" ")),t.isArray(e)&&(e={left:+e[0],top:+e[1]||0}),"left"in e&&(this.offset.click.left=e.left+this.margins.left),"right"in e&&(this.offset.click.left=this.helperProportions.width-e.right+this.margins.left),"top"in e&&(this.offset.click.top=e.top+this.margins.top),"bottom"in e&&(this.offset.click.top=this.helperProportions.height-e.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var e=this.offsetParent.offset();return"absolute"===this.cssPosition&&this.scrollParent[0]!==this.document[0]&&t.contains(this.scrollParent[0],this.offsetParent[0])&&(e.left+=this.scrollParent.scrollLeft(),e.top+=this.scrollParent.scrollTop()),(this.offsetParent[0]===this.document[0].body||this.offsetParent[0].tagName&&"html"===this.offsetParent[0].tagName.toLowerCase()&&t.ui.ie)&&(e={top:0,left:0}),{top:e.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:e.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"===this.cssPosition){var t=this.currentItem.position();return{top:t.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:t.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.currentItem.css("marginLeft"),10)||0,top:parseInt(this.currentItem.css("marginTop"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var e,i,s,n=this.options;"parent"===n.containment&&(n.containment=this.helper[0].parentNode),("document"===n.containment||"window"===n.containment)&&(this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,"document"===n.containment?this.document.width():this.window.width()-this.helperProportions.width-this.margins.left,("document"===n.containment?this.document.height()||document.body.parentNode.scrollHeight:this.window.height()||this.document[0].body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]),/^(document|window|parent)$/.test(n.containment)||(e=t(n.containment)[0],i=t(n.containment).offset(),s="hidden"!==t(e).css("overflow"),this.containment=[i.left+(parseInt(t(e).css("borderLeftWidth"),10)||0)+(parseInt(t(e).css("paddingLeft"),10)||0)-this.margins.left,i.top+(parseInt(t(e).css("borderTopWidth"),10)||0)+(parseInt(t(e).css("paddingTop"),10)||0)-this.margins.top,i.left+(s?Math.max(e.scrollWidth,e.offsetWidth):e.offsetWidth)-(parseInt(t(e).css("borderLeftWidth"),10)||0)-(parseInt(t(e).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,i.top+(s?Math.max(e.scrollHeight,e.offsetHeight):e.offsetHeight)-(parseInt(t(e).css("borderTopWidth"),10)||0)-(parseInt(t(e).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top])},_convertPositionTo:function(e,i){i||(i=this.position);var s="absolute"===e?1:-1,n="absolute"!==this.cssPosition||this.scrollParent[0]!==this.document[0]&&t.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,o=/(html|body)/i.test(n[0].tagName);return{top:i.top+this.offset.relative.top*s+this.offset.parent.top*s-("fixed"===this.cssPosition?-this.scrollParent.scrollTop():o?0:n.scrollTop())*s,left:i.left+this.offset.relative.left*s+this.offset.parent.left*s-("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():o?0:n.scrollLeft())*s}},_generatePosition:function(e){var i,s,n=this.options,o=e.pageX,a=e.pageY,r="absolute"!==this.cssPosition||this.scrollParent[0]!==this.document[0]&&t.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,h=/(html|body)/i.test(r[0].tagName);return"relative"!==this.cssPosition||this.scrollParent[0]!==this.document[0]&&this.scrollParent[0]!==this.offsetParent[0]||(this.offset.relative=this._getRelativeOffset()),this.originalPosition&&(this.containment&&(e.pageX-this.offset.click.left<this.containment[0]&&(o=this.containment[0]+this.offset.click.left),e.pageY-this.offset.click.top<this.containment[1]&&(a=this.containment[1]+this.offset.click.top),e.pageX-this.offset.click.left>this.containment[2]&&(o=this.containment[2]+this.offset.click.left),e.pageY-this.offset.click.top>this.containment[3]&&(a=this.containment[3]+this.offset.click.top)),n.grid&&(i=this.originalPageY+Math.round((a-this.originalPageY)/n.grid[1])*n.grid[1],a=this.containment?i-this.offset.click.top>=this.containment[1]&&i-this.offset.click.top<=this.containment[3]?i:i-this.offset.click.top>=this.containment[1]?i-n.grid[1]:i+n.grid[1]:i,s=this.originalPageX+Math.round((o-this.originalPageX)/n.grid[0])*n.grid[0],o=this.containment?s-this.offset.click.left>=this.containment[0]&&s-this.offset.click.left<=this.containment[2]?s:s-this.offset.click.left>=this.containment[0]?s-n.grid[0]:s+n.grid[0]:s)),{top:a-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.scrollParent.scrollTop():h?0:r.scrollTop()),left:o-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():h?0:r.scrollLeft())}},_rearrange:function(t,e,i,s){i?i[0].appendChild(this.placeholder[0]):e.item[0].parentNode.insertBefore(this.placeholder[0],"down"===this.direction?e.item[0]:e.item[0].nextSibling),this.counter=this.counter?++this.counter:1;var n=this.counter;
this._delay(function(){n===this.counter&&this.refreshPositions(!s)})},_clear:function(t,e){function i(t,e,i){return function(s){i._trigger(t,s,e._uiHash(e))}}this.reverting=!1;var s,n=[];if(!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem),this._noFinalSort=null,this.helper[0]===this.currentItem[0]){for(s in this._storedCSS)("auto"===this._storedCSS[s]||"static"===this._storedCSS[s])&&(this._storedCSS[s]="");this.currentItem.css(this._storedCSS),this._removeClass(this.currentItem,"ui-sortable-helper")}else this.currentItem.show();for(this.fromOutside&&!e&&n.push(function(t){this._trigger("receive",t,this._uiHash(this.fromOutside))}),!this.fromOutside&&this.domPosition.prev===this.currentItem.prev().not(".ui-sortable-helper")[0]&&this.domPosition.parent===this.currentItem.parent()[0]||e||n.push(function(t){this._trigger("update",t,this._uiHash())}),this!==this.currentContainer&&(e||(n.push(function(t){this._trigger("remove",t,this._uiHash())}),n.push(function(t){return function(e){t._trigger("receive",e,this._uiHash(this))}}.call(this,this.currentContainer)),n.push(function(t){return function(e){t._trigger("update",e,this._uiHash(this))}}.call(this,this.currentContainer)))),s=this.containers.length-1;s>=0;s--)e||n.push(i("deactivate",this,this.containers[s])),this.containers[s].containerCache.over&&(n.push(i("out",this,this.containers[s])),this.containers[s].containerCache.over=0);if(this.storedCursor&&(this.document.find("body").css("cursor",this.storedCursor),this.storedStylesheet.remove()),this._storedOpacity&&this.helper.css("opacity",this._storedOpacity),this._storedZIndex&&this.helper.css("zIndex","auto"===this._storedZIndex?"":this._storedZIndex),this.dragging=!1,e||this._trigger("beforeStop",t,this._uiHash()),this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.cancelHelperRemoval||(this.helper[0]!==this.currentItem[0]&&this.helper.remove(),this.helper=null),!e){for(s=0;n.length>s;s++)n[s].call(this,t);this._trigger("stop",t,this._uiHash())}return this.fromOutside=!1,!this.cancelHelperRemoval},_trigger:function(){t.Widget.prototype._trigger.apply(this,arguments)===!1&&this.cancel()},_uiHash:function(e){var i=e||this;return{helper:i.helper,placeholder:i.placeholder||t([]),position:i.position,originalPosition:i.originalPosition,offset:i.positionAbs,item:i.currentItem,sender:e?e.element:null}}}),t.widget("ui.spinner",{version:"1.12.1",defaultElement:"<input>",widgetEventPrefix:"spin",options:{classes:{"ui-spinner":"ui-corner-all","ui-spinner-down":"ui-corner-br","ui-spinner-up":"ui-corner-tr"},culture:null,icons:{down:"ui-icon-triangle-1-s",up:"ui-icon-triangle-1-n"},incremental:!0,max:null,min:null,numberFormat:null,page:10,step:1,change:null,spin:null,start:null,stop:null},_create:function(){this._setOption("max",this.options.max),this._setOption("min",this.options.min),this._setOption("step",this.options.step),""!==this.value()&&this._value(this.element.val(),!0),this._draw(),this._on(this._events),this._refresh(),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_getCreateOptions:function(){var e=this._super(),i=this.element;return t.each(["min","max","step"],function(t,s){var n=i.attr(s);null!=n&&n.length&&(e[s]=n)}),e},_events:{keydown:function(t){this._start(t)&&this._keydown(t)&&t.preventDefault()},keyup:"_stop",focus:function(){this.previous=this.element.val()},blur:function(t){return this.cancelBlur?(delete this.cancelBlur,void 0):(this._stop(),this._refresh(),this.previous!==this.element.val()&&this._trigger("change",t),void 0)},mousewheel:function(t,e){if(e){if(!this.spinning&&!this._start(t))return!1;this._spin((e>0?1:-1)*this.options.step,t),clearTimeout(this.mousewheelTimer),this.mousewheelTimer=this._delay(function(){this.spinning&&this._stop(t)},100),t.preventDefault()}},"mousedown .ui-spinner-button":function(e){function i(){var e=this.element[0]===t.ui.safeActiveElement(this.document[0]);e||(this.element.trigger("focus"),this.previous=s,this._delay(function(){this.previous=s}))}var s;s=this.element[0]===t.ui.safeActiveElement(this.document[0])?this.previous:this.element.val(),e.preventDefault(),i.call(this),this.cancelBlur=!0,this._delay(function(){delete this.cancelBlur,i.call(this)}),this._start(e)!==!1&&this._repeat(null,t(e.currentTarget).hasClass("ui-spinner-up")?1:-1,e)},"mouseup .ui-spinner-button":"_stop","mouseenter .ui-spinner-button":function(e){return t(e.currentTarget).hasClass("ui-state-active")?this._start(e)===!1?!1:(this._repeat(null,t(e.currentTarget).hasClass("ui-spinner-up")?1:-1,e),void 0):void 0},"mouseleave .ui-spinner-button":"_stop"},_enhance:function(){this.uiSpinner=this.element.attr("autocomplete","off").wrap("<span>").parent().append("<a></a><a></a>")},_draw:function(){this._enhance(),this._addClass(this.uiSpinner,"ui-spinner","ui-widget ui-widget-content"),this._addClass("ui-spinner-input"),this.element.attr("role","spinbutton"),this.buttons=this.uiSpinner.children("a").attr("tabIndex",-1).attr("aria-hidden",!0).button({classes:{"ui-button":""}}),this._removeClass(this.buttons,"ui-corner-all"),this._addClass(this.buttons.first(),"ui-spinner-button ui-spinner-up"),this._addClass(this.buttons.last(),"ui-spinner-button ui-spinner-down"),this.buttons.first().button({icon:this.options.icons.up,showLabel:!1}),this.buttons.last().button({icon:this.options.icons.down,showLabel:!1}),this.buttons.height()>Math.ceil(.5*this.uiSpinner.height())&&this.uiSpinner.height()>0&&this.uiSpinner.height(this.uiSpinner.height())},_keydown:function(e){var i=this.options,s=t.ui.keyCode;switch(e.keyCode){case s.UP:return this._repeat(null,1,e),!0;case s.DOWN:return this._repeat(null,-1,e),!0;case s.PAGE_UP:return this._repeat(null,i.page,e),!0;case s.PAGE_DOWN:return this._repeat(null,-i.page,e),!0}return!1},_start:function(t){return this.spinning||this._trigger("start",t)!==!1?(this.counter||(this.counter=1),this.spinning=!0,!0):!1},_repeat:function(t,e,i){t=t||500,clearTimeout(this.timer),this.timer=this._delay(function(){this._repeat(40,e,i)},t),this._spin(e*this.options.step,i)},_spin:function(t,e){var i=this.value()||0;this.counter||(this.counter=1),i=this._adjustValue(i+t*this._increment(this.counter)),this.spinning&&this._trigger("spin",e,{value:i})===!1||(this._value(i),this.counter++)},_increment:function(e){var i=this.options.incremental;return i?t.isFunction(i)?i(e):Math.floor(e*e*e/5e4-e*e/500+17*e/200+1):1},_precision:function(){var t=this._precisionOf(this.options.step);return null!==this.options.min&&(t=Math.max(t,this._precisionOf(this.options.min))),t},_precisionOf:function(t){var e=""+t,i=e.indexOf(".");return-1===i?0:e.length-i-1},_adjustValue:function(t){var e,i,s=this.options;return e=null!==s.min?s.min:0,i=t-e,i=Math.round(i/s.step)*s.step,t=e+i,t=parseFloat(t.toFixed(this._precision())),null!==s.max&&t>s.max?s.max:null!==s.min&&s.min>t?s.min:t},_stop:function(t){this.spinning&&(clearTimeout(this.timer),clearTimeout(this.mousewheelTimer),this.counter=0,this.spinning=!1,this._trigger("stop",t))},_setOption:function(t,e){var i,s,n;return"culture"===t||"numberFormat"===t?(i=this._parse(this.element.val()),this.options[t]=e,this.element.val(this._format(i)),void 0):(("max"===t||"min"===t||"step"===t)&&"string"==typeof e&&(e=this._parse(e)),"icons"===t&&(s=this.buttons.first().find(".ui-icon"),this._removeClass(s,null,this.options.icons.up),this._addClass(s,null,e.up),n=this.buttons.last().find(".ui-icon"),this._removeClass(n,null,this.options.icons.down),this._addClass(n,null,e.down)),this._super(t,e),void 0)},_setOptionDisabled:function(t){this._super(t),this._toggleClass(this.uiSpinner,null,"ui-state-disabled",!!t),this.element.prop("disabled",!!t),this.buttons.button(t?"disable":"enable")},_setOptions:r(function(t){this._super(t)}),_parse:function(t){return"string"==typeof t&&""!==t&&(t=window.Globalize&&this.options.numberFormat?Globalize.parseFloat(t,10,this.options.culture):+t),""===t||isNaN(t)?null:t},_format:function(t){return""===t?"":window.Globalize&&this.options.numberFormat?Globalize.format(t,this.options.numberFormat,this.options.culture):t},_refresh:function(){this.element.attr({"aria-valuemin":this.options.min,"aria-valuemax":this.options.max,"aria-valuenow":this._parse(this.element.val())})},isValid:function(){var t=this.value();return null===t?!1:t===this._adjustValue(t)},_value:function(t,e){var i;""!==t&&(i=this._parse(t),null!==i&&(e||(i=this._adjustValue(i)),t=this._format(i))),this.element.val(t),this._refresh()},_destroy:function(){this.element.prop("disabled",!1).removeAttr("autocomplete role aria-valuemin aria-valuemax aria-valuenow"),this.uiSpinner.replaceWith(this.element)},stepUp:r(function(t){this._stepUp(t)}),_stepUp:function(t){this._start()&&(this._spin((t||1)*this.options.step),this._stop())},stepDown:r(function(t){this._stepDown(t)}),_stepDown:function(t){this._start()&&(this._spin((t||1)*-this.options.step),this._stop())},pageUp:r(function(t){this._stepUp((t||1)*this.options.page)}),pageDown:r(function(t){this._stepDown((t||1)*this.options.page)}),value:function(t){return arguments.length?(r(this._value).call(this,t),void 0):this._parse(this.element.val())},widget:function(){return this.uiSpinner}}),t.uiBackCompat!==!1&&t.widget("ui.spinner",t.ui.spinner,{_enhance:function(){this.uiSpinner=this.element.attr("autocomplete","off").wrap(this._uiSpinnerHtml()).parent().append(this._buttonHtml())},_uiSpinnerHtml:function(){return"<span>"},_buttonHtml:function(){return"<a></a><a></a>"}}),t.ui.spinner,t.widget("ui.tabs",{version:"1.12.1",delay:300,options:{active:null,classes:{"ui-tabs":"ui-corner-all","ui-tabs-nav":"ui-corner-all","ui-tabs-panel":"ui-corner-bottom","ui-tabs-tab":"ui-corner-top"},collapsible:!1,event:"click",heightStyle:"content",hide:null,show:null,activate:null,beforeActivate:null,beforeLoad:null,load:null},_isLocal:function(){var t=/#.*$/;return function(e){var i,s;i=e.href.replace(t,""),s=location.href.replace(t,"");try{i=decodeURIComponent(i)}catch(n){}try{s=decodeURIComponent(s)}catch(n){}return e.hash.length>1&&i===s}}(),_create:function(){var e=this,i=this.options;this.running=!1,this._addClass("ui-tabs","ui-widget ui-widget-content"),this._toggleClass("ui-tabs-collapsible",null,i.collapsible),this._processTabs(),i.active=this._initialActive(),t.isArray(i.disabled)&&(i.disabled=t.unique(i.disabled.concat(t.map(this.tabs.filter(".ui-state-disabled"),function(t){return e.tabs.index(t)}))).sort()),this.active=this.options.active!==!1&&this.anchors.length?this._findActive(i.active):t(),this._refresh(),this.active.length&&this.load(i.active)},_initialActive:function(){var e=this.options.active,i=this.options.collapsible,s=location.hash.substring(1);return null===e&&(s&&this.tabs.each(function(i,n){return t(n).attr("aria-controls")===s?(e=i,!1):void 0}),null===e&&(e=this.tabs.index(this.tabs.filter(".ui-tabs-active"))),(null===e||-1===e)&&(e=this.tabs.length?0:!1)),e!==!1&&(e=this.tabs.index(this.tabs.eq(e)),-1===e&&(e=i?!1:0)),!i&&e===!1&&this.anchors.length&&(e=0),e},_getCreateEventData:function(){return{tab:this.active,panel:this.active.length?this._getPanelForTab(this.active):t()}},_tabKeydown:function(e){var i=t(t.ui.safeActiveElement(this.document[0])).closest("li"),s=this.tabs.index(i),n=!0;if(!this._handlePageNav(e)){switch(e.keyCode){case t.ui.keyCode.RIGHT:case t.ui.keyCode.DOWN:s++;break;case t.ui.keyCode.UP:case t.ui.keyCode.LEFT:n=!1,s--;break;case t.ui.keyCode.END:s=this.anchors.length-1;break;case t.ui.keyCode.HOME:s=0;break;case t.ui.keyCode.SPACE:return e.preventDefault(),clearTimeout(this.activating),this._activate(s),void 0;case t.ui.keyCode.ENTER:return e.preventDefault(),clearTimeout(this.activating),this._activate(s===this.options.active?!1:s),void 0;default:return}e.preventDefault(),clearTimeout(this.activating),s=this._focusNextTab(s,n),e.ctrlKey||e.metaKey||(i.attr("aria-selected","false"),this.tabs.eq(s).attr("aria-selected","true"),this.activating=this._delay(function(){this.option("active",s)},this.delay))}},_panelKeydown:function(e){this._handlePageNav(e)||e.ctrlKey&&e.keyCode===t.ui.keyCode.UP&&(e.preventDefault(),this.active.trigger("focus"))},_handlePageNav:function(e){return e.altKey&&e.keyCode===t.ui.keyCode.PAGE_UP?(this._activate(this._focusNextTab(this.options.active-1,!1)),!0):e.altKey&&e.keyCode===t.ui.keyCode.PAGE_DOWN?(this._activate(this._focusNextTab(this.options.active+1,!0)),!0):void 0},_findNextTab:function(e,i){function s(){return e>n&&(e=0),0>e&&(e=n),e}for(var n=this.tabs.length-1;-1!==t.inArray(s(),this.options.disabled);)e=i?e+1:e-1;return e},_focusNextTab:function(t,e){return t=this._findNextTab(t,e),this.tabs.eq(t).trigger("focus"),t},_setOption:function(t,e){return"active"===t?(this._activate(e),void 0):(this._super(t,e),"collapsible"===t&&(this._toggleClass("ui-tabs-collapsible",null,e),e||this.options.active!==!1||this._activate(0)),"event"===t&&this._setupEvents(e),"heightStyle"===t&&this._setupHeightStyle(e),void 0)},_sanitizeSelector:function(t){return t?t.replace(/[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g,"\\$&"):""},refresh:function(){var e=this.options,i=this.tablist.children(":has(a[href])");e.disabled=t.map(i.filter(".ui-state-disabled"),function(t){return i.index(t)}),this._processTabs(),e.active!==!1&&this.anchors.length?this.active.length&&!t.contains(this.tablist[0],this.active[0])?this.tabs.length===e.disabled.length?(e.active=!1,this.active=t()):this._activate(this._findNextTab(Math.max(0,e.active-1),!1)):e.active=this.tabs.index(this.active):(e.active=!1,this.active=t()),this._refresh()},_refresh:function(){this._setOptionDisabled(this.options.disabled),this._setupEvents(this.options.event),this._setupHeightStyle(this.options.heightStyle),this.tabs.not(this.active).attr({"aria-selected":"false","aria-expanded":"false",tabIndex:-1}),this.panels.not(this._getPanelForTab(this.active)).hide().attr({"aria-hidden":"true"}),this.active.length?(this.active.attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0}),this._addClass(this.active,"ui-tabs-active","ui-state-active"),this._getPanelForTab(this.active).show().attr({"aria-hidden":"false"})):this.tabs.eq(0).attr("tabIndex",0)},_processTabs:function(){var e=this,i=this.tabs,s=this.anchors,n=this.panels;this.tablist=this._getList().attr("role","tablist"),this._addClass(this.tablist,"ui-tabs-nav","ui-helper-reset ui-helper-clearfix ui-widget-header"),this.tablist.on("mousedown"+this.eventNamespace,"> li",function(e){t(this).is(".ui-state-disabled")&&e.preventDefault()}).on("focus"+this.eventNamespace,".ui-tabs-anchor",function(){t(this).closest("li").is(".ui-state-disabled")&&this.blur()}),this.tabs=this.tablist.find("> li:has(a[href])").attr({role:"tab",tabIndex:-1}),this._addClass(this.tabs,"ui-tabs-tab","ui-state-default"),this.anchors=this.tabs.map(function(){return t("a",this)[0]}).attr({role:"presentation",tabIndex:-1}),this._addClass(this.anchors,"ui-tabs-anchor"),this.panels=t(),this.anchors.each(function(i,s){var n,o,a,r=t(s).uniqueId().attr("id"),h=t(s).closest("li"),l=h.attr("aria-controls");e._isLocal(s)?(n=s.hash,a=n.substring(1),o=e.element.find(e._sanitizeSelector(n))):(a=h.attr("aria-controls")||t({}).uniqueId()[0].id,n="#"+a,o=e.element.find(n),o.length||(o=e._createPanel(a),o.insertAfter(e.panels[i-1]||e.tablist)),o.attr("aria-live","polite")),o.length&&(e.panels=e.panels.add(o)),l&&h.data("ui-tabs-aria-controls",l),h.attr({"aria-controls":a,"aria-labelledby":r}),o.attr("aria-labelledby",r)}),this.panels.attr("role","tabpanel"),this._addClass(this.panels,"ui-tabs-panel","ui-widget-content"),i&&(this._off(i.not(this.tabs)),this._off(s.not(this.anchors)),this._off(n.not(this.panels)))},_getList:function(){return this.tablist||this.element.find("ol, ul").eq(0)},_createPanel:function(e){return t("<div>").attr("id",e).data("ui-tabs-destroy",!0)},_setOptionDisabled:function(e){var i,s,n;for(t.isArray(e)&&(e.length?e.length===this.anchors.length&&(e=!0):e=!1),n=0;s=this.tabs[n];n++)i=t(s),e===!0||-1!==t.inArray(n,e)?(i.attr("aria-disabled","true"),this._addClass(i,null,"ui-state-disabled")):(i.removeAttr("aria-disabled"),this._removeClass(i,null,"ui-state-disabled"));this.options.disabled=e,this._toggleClass(this.widget(),this.widgetFullName+"-disabled",null,e===!0)},_setupEvents:function(e){var i={};e&&t.each(e.split(" "),function(t,e){i[e]="_eventHandler"}),this._off(this.anchors.add(this.tabs).add(this.panels)),this._on(!0,this.anchors,{click:function(t){t.preventDefault()}}),this._on(this.anchors,i),this._on(this.tabs,{keydown:"_tabKeydown"}),this._on(this.panels,{keydown:"_panelKeydown"}),this._focusable(this.tabs),this._hoverable(this.tabs)},_setupHeightStyle:function(e){var i,s=this.element.parent();"fill"===e?(i=s.height(),i-=this.element.outerHeight()-this.element.height(),this.element.siblings(":visible").each(function(){var e=t(this),s=e.css("position");"absolute"!==s&&"fixed"!==s&&(i-=e.outerHeight(!0))}),this.element.children().not(this.panels).each(function(){i-=t(this).outerHeight(!0)}),this.panels.each(function(){t(this).height(Math.max(0,i-t(this).innerHeight()+t(this).height()))}).css("overflow","auto")):"auto"===e&&(i=0,this.panels.each(function(){i=Math.max(i,t(this).height("").height())}).height(i))},_eventHandler:function(e){var i=this.options,s=this.active,n=t(e.currentTarget),o=n.closest("li"),a=o[0]===s[0],r=a&&i.collapsible,h=r?t():this._getPanelForTab(o),l=s.length?this._getPanelForTab(s):t(),c={oldTab:s,oldPanel:l,newTab:r?t():o,newPanel:h};e.preventDefault(),o.hasClass("ui-state-disabled")||o.hasClass("ui-tabs-loading")||this.running||a&&!i.collapsible||this._trigger("beforeActivate",e,c)===!1||(i.active=r?!1:this.tabs.index(o),this.active=a?t():o,this.xhr&&this.xhr.abort(),l.length||h.length||t.error("jQuery UI Tabs: Mismatching fragment identifier."),h.length&&this.load(this.tabs.index(o),e),this._toggle(e,c))},_toggle:function(e,i){function s(){o.running=!1,o._trigger("activate",e,i)}function n(){o._addClass(i.newTab.closest("li"),"ui-tabs-active","ui-state-active"),a.length&&o.options.show?o._show(a,o.options.show,s):(a.show(),s())}var o=this,a=i.newPanel,r=i.oldPanel;this.running=!0,r.length&&this.options.hide?this._hide(r,this.options.hide,function(){o._removeClass(i.oldTab.closest("li"),"ui-tabs-active","ui-state-active"),n()}):(this._removeClass(i.oldTab.closest("li"),"ui-tabs-active","ui-state-active"),r.hide(),n()),r.attr("aria-hidden","true"),i.oldTab.attr({"aria-selected":"false","aria-expanded":"false"}),a.length&&r.length?i.oldTab.attr("tabIndex",-1):a.length&&this.tabs.filter(function(){return 0===t(this).attr("tabIndex")}).attr("tabIndex",-1),a.attr("aria-hidden","false"),i.newTab.attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0})},_activate:function(e){var i,s=this._findActive(e);s[0]!==this.active[0]&&(s.length||(s=this.active),i=s.find(".ui-tabs-anchor")[0],this._eventHandler({target:i,currentTarget:i,preventDefault:t.noop}))},_findActive:function(e){return e===!1?t():this.tabs.eq(e)},_getIndex:function(e){return"string"==typeof e&&(e=this.anchors.index(this.anchors.filter("[href$='"+t.ui.escapeSelector(e)+"']"))),e},_destroy:function(){this.xhr&&this.xhr.abort(),this.tablist.removeAttr("role").off(this.eventNamespace),this.anchors.removeAttr("role tabIndex").removeUniqueId(),this.tabs.add(this.panels).each(function(){t.data(this,"ui-tabs-destroy")?t(this).remove():t(this).removeAttr("role tabIndex aria-live aria-busy aria-selected aria-labelledby aria-hidden aria-expanded")}),this.tabs.each(function(){var e=t(this),i=e.data("ui-tabs-aria-controls");i?e.attr("aria-controls",i).removeData("ui-tabs-aria-controls"):e.removeAttr("aria-controls")}),this.panels.show(),"content"!==this.options.heightStyle&&this.panels.css("height","")},enable:function(e){var i=this.options.disabled;i!==!1&&(void 0===e?i=!1:(e=this._getIndex(e),i=t.isArray(i)?t.map(i,function(t){return t!==e?t:null}):t.map(this.tabs,function(t,i){return i!==e?i:null})),this._setOptionDisabled(i))},disable:function(e){var i=this.options.disabled;if(i!==!0){if(void 0===e)i=!0;else{if(e=this._getIndex(e),-1!==t.inArray(e,i))return;i=t.isArray(i)?t.merge([e],i).sort():[e]}this._setOptionDisabled(i)}},load:function(e,i){e=this._getIndex(e);var s=this,n=this.tabs.eq(e),o=n.find(".ui-tabs-anchor"),a=this._getPanelForTab(n),r={tab:n,panel:a},h=function(t,e){"abort"===e&&s.panels.stop(!1,!0),s._removeClass(n,"ui-tabs-loading"),a.removeAttr("aria-busy"),t===s.xhr&&delete s.xhr};this._isLocal(o[0])||(this.xhr=t.ajax(this._ajaxSettings(o,i,r)),this.xhr&&"canceled"!==this.xhr.statusText&&(this._addClass(n,"ui-tabs-loading"),a.attr("aria-busy","true"),this.xhr.done(function(t,e,n){setTimeout(function(){a.html(t),s._trigger("load",i,r),h(n,e)},1)}).fail(function(t,e){setTimeout(function(){h(t,e)},1)})))},_ajaxSettings:function(e,i,s){var n=this;return{url:e.attr("href").replace(/#.*$/,""),beforeSend:function(e,o){return n._trigger("beforeLoad",i,t.extend({jqXHR:e,ajaxSettings:o},s))}}},_getPanelForTab:function(e){var i=t(e).attr("aria-controls");return this.element.find(this._sanitizeSelector("#"+i))}}),t.uiBackCompat!==!1&&t.widget("ui.tabs",t.ui.tabs,{_processTabs:function(){this._superApply(arguments),this._addClass(this.tabs,"ui-tab")}}),t.ui.tabs,t.widget("ui.tooltip",{version:"1.12.1",options:{classes:{"ui-tooltip":"ui-corner-all ui-widget-shadow"},content:function(){var e=t(this).attr("title")||"";return t("<a>").text(e).html()},hide:!0,items:"[title]:not([disabled])",position:{my:"left top+15",at:"left bottom",collision:"flipfit flip"},show:!0,track:!1,close:null,open:null},_addDescribedBy:function(e,i){var s=(e.attr("aria-describedby")||"").split(/\s+/);s.push(i),e.data("ui-tooltip-id",i).attr("aria-describedby",t.trim(s.join(" ")))},_removeDescribedBy:function(e){var i=e.data("ui-tooltip-id"),s=(e.attr("aria-describedby")||"").split(/\s+/),n=t.inArray(i,s);-1!==n&&s.splice(n,1),e.removeData("ui-tooltip-id"),s=t.trim(s.join(" ")),s?e.attr("aria-describedby",s):e.removeAttr("aria-describedby")},_create:function(){this._on({mouseover:"open",focusin:"open"}),this.tooltips={},this.parents={},this.liveRegion=t("<div>").attr({role:"log","aria-live":"assertive","aria-relevant":"additions"}).appendTo(this.document[0].body),this._addClass(this.liveRegion,null,"ui-helper-hidden-accessible"),this.disabledTitles=t([])},_setOption:function(e,i){var s=this;this._super(e,i),"content"===e&&t.each(this.tooltips,function(t,e){s._updateContent(e.element)})},_setOptionDisabled:function(t){this[t?"_disable":"_enable"]()},_disable:function(){var e=this;t.each(this.tooltips,function(i,s){var n=t.Event("blur");n.target=n.currentTarget=s.element[0],e.close(n,!0)}),this.disabledTitles=this.disabledTitles.add(this.element.find(this.options.items).addBack().filter(function(){var e=t(this);return e.is("[title]")?e.data("ui-tooltip-title",e.attr("title")).removeAttr("title"):void 0}))},_enable:function(){this.disabledTitles.each(function(){var e=t(this);e.data("ui-tooltip-title")&&e.attr("title",e.data("ui-tooltip-title"))}),this.disabledTitles=t([])},open:function(e){var i=this,s=t(e?e.target:this.element).closest(this.options.items);s.length&&!s.data("ui-tooltip-id")&&(s.attr("title")&&s.data("ui-tooltip-title",s.attr("title")),s.data("ui-tooltip-open",!0),e&&"mouseover"===e.type&&s.parents().each(function(){var e,s=t(this);s.data("ui-tooltip-open")&&(e=t.Event("blur"),e.target=e.currentTarget=this,i.close(e,!0)),s.attr("title")&&(s.uniqueId(),i.parents[this.id]={element:this,title:s.attr("title")},s.attr("title",""))}),this._registerCloseHandlers(e,s),this._updateContent(s,e))},_updateContent:function(t,e){var i,s=this.options.content,n=this,o=e?e.type:null;return"string"==typeof s||s.nodeType||s.jquery?this._open(e,t,s):(i=s.call(t[0],function(i){n._delay(function(){t.data("ui-tooltip-open")&&(e&&(e.type=o),this._open(e,t,i))})}),i&&this._open(e,t,i),void 0)},_open:function(e,i,s){function n(t){l.of=t,a.is(":hidden")||a.position(l)}var o,a,r,h,l=t.extend({},this.options.position);if(s){if(o=this._find(i))return o.tooltip.find(".ui-tooltip-content").html(s),void 0;i.is("[title]")&&(e&&"mouseover"===e.type?i.attr("title",""):i.removeAttr("title")),o=this._tooltip(i),a=o.tooltip,this._addDescribedBy(i,a.attr("id")),a.find(".ui-tooltip-content").html(s),this.liveRegion.children().hide(),h=t("<div>").html(a.find(".ui-tooltip-content").html()),h.removeAttr("name").find("[name]").removeAttr("name"),h.removeAttr("id").find("[id]").removeAttr("id"),h.appendTo(this.liveRegion),this.options.track&&e&&/^mouse/.test(e.type)?(this._on(this.document,{mousemove:n}),n(e)):a.position(t.extend({of:i},this.options.position)),a.hide(),this._show(a,this.options.show),this.options.track&&this.options.show&&this.options.show.delay&&(r=this.delayedShow=setInterval(function(){a.is(":visible")&&(n(l.of),clearInterval(r))},t.fx.interval)),this._trigger("open",e,{tooltip:a})}},_registerCloseHandlers:function(e,i){var s={keyup:function(e){if(e.keyCode===t.ui.keyCode.ESCAPE){var s=t.Event(e);s.currentTarget=i[0],this.close(s,!0)}}};i[0]!==this.element[0]&&(s.remove=function(){this._removeTooltip(this._find(i).tooltip)}),e&&"mouseover"!==e.type||(s.mouseleave="close"),e&&"focusin"!==e.type||(s.focusout="close"),this._on(!0,i,s)},close:function(e){var i,s=this,n=t(e?e.currentTarget:this.element),o=this._find(n);return o?(i=o.tooltip,o.closing||(clearInterval(this.delayedShow),n.data("ui-tooltip-title")&&!n.attr("title")&&n.attr("title",n.data("ui-tooltip-title")),this._removeDescribedBy(n),o.hiding=!0,i.stop(!0),this._hide(i,this.options.hide,function(){s._removeTooltip(t(this))}),n.removeData("ui-tooltip-open"),this._off(n,"mouseleave focusout keyup"),n[0]!==this.element[0]&&this._off(n,"remove"),this._off(this.document,"mousemove"),e&&"mouseleave"===e.type&&t.each(this.parents,function(e,i){t(i.element).attr("title",i.title),delete s.parents[e]}),o.closing=!0,this._trigger("close",e,{tooltip:i}),o.hiding||(o.closing=!1)),void 0):(n.removeData("ui-tooltip-open"),void 0)},_tooltip:function(e){var i=t("<div>").attr("role","tooltip"),s=t("<div>").appendTo(i),n=i.uniqueId().attr("id");return this._addClass(s,"ui-tooltip-content"),this._addClass(i,"ui-tooltip","ui-widget ui-widget-content"),i.appendTo(this._appendTo(e)),this.tooltips[n]={element:e,tooltip:i}},_find:function(t){var e=t.data("ui-tooltip-id");return e?this.tooltips[e]:null},_removeTooltip:function(t){t.remove(),delete this.tooltips[t.attr("id")]},_appendTo:function(t){var e=t.closest(".ui-front, dialog");return e.length||(e=this.document[0].body),e},_destroy:function(){var e=this;t.each(this.tooltips,function(i,s){var n=t.Event("blur"),o=s.element;n.target=n.currentTarget=o[0],e.close(n,!0),t("#"+i).remove(),o.data("ui-tooltip-title")&&(o.attr("title")||o.attr("title",o.data("ui-tooltip-title")),o.removeData("ui-tooltip-title"))}),this.liveRegion.remove()}}),t.uiBackCompat!==!1&&t.widget("ui.tooltip",t.ui.tooltip,{options:{tooltipClass:null},_tooltip:function(){var t=this._superApply(arguments);return this.options.tooltipClass&&t.tooltip.addClass(this.options.tooltipClass),t}}),t.ui.tooltip});;
/*
Copyright © 2013 Adobe Systems Incorporated.

Licensed under the Apache License, Version 2.0 (the “License”);
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/**
 * See <a href="http://jquery.com">http://jquery.com</a>.
 * @name jquery
 * @class
 * See the jQuery Library  (<a href="http://jquery.com">http://jquery.com</a>) for full details.  This just
 * documents the function and classes that are added to jQuery by this plug-in.
 */

/**
 * See <a href="http://jquery.com">http://jquery.com</a>
 * @name fn
 * @class
 * See the jQuery Library  (<a href="http://jquery.com">http://jquery.com</a>) for full details.  This just
 * documents the function and classes that are added to jQuery by this plug-in.
 * @memberOf jquery
 */

/**
 * @fileOverview accessibleMegaMenu plugin
 *
 *<p>Licensed under the Apache License, Version 2.0 (the “License”)
 *<br />Copyright © 2013 Adobe Systems Incorporated.
 *<br />Project page <a href="https://github.com/adobe-accessibility/Accessible-Mega-Menu">https://github.com/adobe-accessibility/Accessible-Mega-Menu</a>
 * @version 0.1
 * @author Michael Jordan
 * @requires jquery
 */

/*jslint browser: true, devel: true, plusplus: true, nomen: true */
/*global jQuery */
(function ($, window, document) {
    "use strict";
    var pluginName = "accessibleMegaMenu",
        defaults = {
            uuidPrefix: "accessible-megamenu", // unique ID's are required to indicate aria-owns, aria-controls and aria-labelledby
            menuClass: "accessible-megamenu", // default css class used to define the megamenu styling
            topNavItemClass: "accessible-megamenu-top-nav-item", // default css class for a top-level navigation item in the megamenu
            panelClass: "accessible-megamenu-panel", // default css class for a megamenu panel
            panelGroupClass: "accessible-megamenu-panel-group", // default css class for a group of items within a megamenu panel
            hoverClass: "hover", // default css class for the hover state
            focusClass: "focus", // default css class for the focus state
            openClass: "open" // default css class for the open state
        },
        Keyboard = {
            BACKSPACE: 8,
            COMMA: 188,
            DELETE: 46,
            DOWN: 40,
            END: 35,
            ENTER: 13,
            ESCAPE: 27,
            HOME: 36,
            LEFT: 37,
            PAGE_DOWN: 34,
            PAGE_UP: 33,
            PERIOD: 190,
            RIGHT: 39,
            SPACE: 32,
            TAB: 9,
            UP: 38,
            keyMap: {
                48: "0",
                49: "1",
                50: "2",
                51: "3",
                52: "4",
                53: "5",
                54: "6",
                55: "7",
                56: "8",
                57: "9",
                59: ";",
                65: "a",
                66: "b",
                67: "c",
                68: "d",
                69: "e",
                70: "f",
                71: "g",
                72: "h",
                73: "i",
                74: "j",
                75: "k",
                76: "l",
                77: "m",
                78: "n",
                79: "o",
                80: "p",
                81: "q",
                82: "r",
                83: "s",
                84: "t",
                85: "u",
                86: "v",
                87: "w",
                88: "x",
                89: "y",
                90: "z",
                96: "0",
                97: "1",
                98: "2",
                99: "3",
                100: "4",
                101: "5",
                102: "6",
                103: "7",
                104: "8",
                105: "9",
                190: "."
            }
        };
    /**
     * @desc Creates a new accessible mega menu instance.
     * @param {jquery} element
     * @param {object} [options] Mega Menu options
     * @param {string} [options.uuidPrefix=accessible-megamenu] - Prefix for generated unique id attributes, which are required to indicate aria-owns, aria-controls and aria-labelledby
     * @param {string} [options.menuClass=accessible-megamenu] - CSS class used to define the megamenu styling
     * @param {string} [options.topNavItemClass=accessible-megamenu-top-nav-item] - CSS class for a top-level navigation item in the megamenu
     * @param {string} [options.panelClass=accessible-megamenu-panel] - CSS class for a megamenu panel
     * @param {string} [options.panelGroupClass=accessible-megamenu-panel-group] - CSS class for a group of items within a megamenu panel
     * @param {string} [options.hoverClass=hover] - CSS class for the hover state
     * @param {string} [options.focusClass=focus] - CSS class for the focus state
     * @param {string} [options.openClass=open] - CSS class for the open state
     * @constructor
     */
    function AccessibleMegaMenu(element, options) {
        this.element = element;

        // merge optional settings and defaults into settings
        this.settings = $.extend({}, defaults, options);

        this._defaults = defaults;
        this._name = pluginName;

        this.mouseTimeoutID = null;
        this.focusTimeoutID = null;
        this.mouseFocused = false;
        this.justFocused = false;

        this.init();
    }

    AccessibleMegaMenu.prototype = (function () {

        /* private attributes and methods ------------------------ */
        var uuid = 0,
            keydownTimeoutDuration = 1000,
            keydownSearchString = "",
            isTouch = typeof window.hasOwnProperty === "function" && !!window.hasOwnProperty("ontouchstart"),
            _getPlugin,
            _addUniqueId,
            _togglePanel,
            _clickHandler,
            _clickOutsideHandler,
            _DOMAttrModifiedHandler,
            _focusInHandler,
            _focusOutHandler,
            _keyDownHandler,
            _mouseDownHandler,
            _mouseOverHandler,
            _mouseOutHandler,
            _toggleExpandedEventHandlers,
            _touchPrevious;

        /* Added _touchPrevious to recall the previous menu item clicked. */

        /**
         * @name jQuery.fn.accessibleMegaMenu~_getPlugin
         * @desc Returns the parent accessibleMegaMenu instance for a given element
         * @param {jQuery} element
         * @memberof jQuery.fn.accessibleMegaMenu
         * @inner
         * @private
         */
        _getPlugin = function (element) {
            return $(element).closest(':data(plugin_' + pluginName + ')').data("plugin_" + pluginName);
        };

        /**
         * @name jQuery.fn.accessibleMegaMenu~_addUniqueId
         * @desc Adds a unique id and element.
         * The id string starts with the
         * string defined in settings.uuidPrefix.
         * @param {jQuery} element
         * @memberof jQuery.fn.accessibleMegaMenu
         * @inner
         * @private
         */
        _addUniqueId = function (element) {
            element = $(element);
            var settings = this.settings;
            if (!element.attr("id")) {
                element.attr("id", settings.uuidPrefix + "-" + new Date().getTime() + "-" + (++uuid));
            }
        };

        /**
         * @name jQuery.fn.accessibleMegaMenu~_togglePanel
         * @desc Toggle the display of mega menu panels in response to an event.
         * The optional boolean value 'hide' forces all panels to hide.
         * @param {event} event
         * @param {Boolean} [hide] Hide all mega menu panels when true
         * @memberof jQuery.fn.accessibleMegaMenu
         * @inner
         * @private
         */
        _togglePanel = function (event, hide) {
            var target = $(event.target),
                that = this,
                settings = this.settings,
                menu = this.menu,
                topli = target.closest('.' + settings.topNavItemClass),
                panel = target.hasClass(settings.panelClass) ? target : target.closest('.' + settings.panelClass),
                newfocus;

            _toggleExpandedEventHandlers.call(this, true);

            if (hide) {
                topli = menu.find('.' + settings.topNavItemClass + ' .' + settings.openClass + ':first').closest('.' + settings.topNavItemClass);
                if (!(topli.is(event.relatedTarget) || topli.has(event.relatedTarget).length > 0)) {
                    if ((event.type === 'mouseout' || event.type === 'focusout') && topli.has(document.activeElement).length > 0) {
                        return;
                    }
                    topli.find('[aria-expanded]')
                        .attr('aria-expanded', 'false')
                        .removeClass(settings.openClass)
                        .filter('.' + settings.panelClass)
                        .attr('aria-hidden', 'true');
                    if ((event.type === 'keydown' && event.keyCode === Keyboard.ESCAPE) || event.type === 'DOMAttrModified') {
                        newfocus = topli.find(':tabbable:first');
                        setTimeout(function () {
                            menu.find('[aria-expanded].' + that.settings.panelClass).off('DOMAttrModified.accessible-megamenu');
                            newfocus.focus();
                            that.justFocused = false;
                        }, 99);
                    }
                } else if (topli.length === 0) {
                    menu.find('[aria-expanded=true]')
                        .attr('aria-expanded', 'false')
                        .removeClass(settings.openClass)
                        .filter('.' + settings.panelClass)
                        .attr('aria-hidden', 'true');
                }
            } else {
                clearTimeout(that.focusTimeoutID);
                topli.siblings()
                    .find('[aria-expanded]')
                    .attr('aria-expanded', 'false')
                    .removeClass(settings.openClass)
                    .filter('.' + settings.panelClass)
                    .attr('aria-hidden', 'true');
                topli.find('[aria-expanded]')
                    .attr('aria-expanded', 'true')
                    .addClass(settings.openClass)
                    .filter('.' + settings.panelClass)
                    .attr('aria-hidden', 'false');
                if (event.type === 'mouseover' && target.is(':tabbable') && topli.length === 1 && panel.length === 0 && menu.has(document.activeElement).length > 0) {
                    target.focus();
                    that.justFocused = false;
                }

                _toggleExpandedEventHandlers.call(that);
            }
        };

        /**
         * @name jQuery.fn.accessibleMegaMenu~_clickHandler
         * @desc Handle click event on mega menu item
         * @param {event} Event object
         * @memberof jQuery.fn.accessibleMegaMenu
         * @inner
         * @private
         */
        _clickHandler = function (event) {
            var target = $(event.currentTarget),
                topli = target.closest('.' + this.settings.topNavItemClass),
                panel = target.closest('.' + this.settings.panelClass);
            if(isTouch && $(event.target)[0].id === '') {
                return; // overcome the issue touch devices clicking a subnav menu link
            }
            if(isTouch){ //check the previous clicked menu item. if same then clicked twice so close the menu
                if($(event.target)[0].id === _touchPrevious) {
                        event.preventDefault();
                        event.stopPropagation();
                        _togglePanel.call(this, event, true);
                        _touchPrevious = null;
                        return;
                } else {
                   _touchPrevious = $(event.target)[0].id;
                }
            }
            if (topli.length === 1
                    && panel.length === 0
                    && topli.find('.' + this.settings.panelClass).length === 1) {
                if (!target.hasClass(this.settings.openClass)) {
                    event.preventDefault();
                    event.stopPropagation();
                    _togglePanel.call(this, event);
                    this.justFocused = false;
                } else {
                    if (this.justFocused) {
                        event.preventDefault();
                        event.stopPropagation();
                        this.justFocused = false;
                    } else if (isTouch) {
                        event.preventDefault();
                        event.stopPropagation();
                        _togglePanel.call(this, event, target.hasClass(this.settings.openClass));
                    }
                }
            } else if(isTouch){ // doesnt make sense but needed for touch to collapse the mennu
                event.preventDefault();
                event.stopPropagation();
                _togglePanel.call(this, event, target.hasClass(this.settings.openClass));
            }
        };

        /**
         * @name jQuery.fn.accessibleMegaMenu~_clickOutsideHandler
         * @desc Handle click event outside of a the megamenu
         * @param {event} Event object
         * @memberof jQuery.fn.accessibleMegaMenu
         * @inner
         * @private
         */
        _clickOutsideHandler = function (event) {
            if ($(event.target).closest(this.menu).length === 0) {
                event.preventDefault();
                event.stopPropagation();
                _togglePanel.call(this, event, true);
            }
        };

        /**
         * @name jQuery.fn.accessibleMegaMenu~_DOMAttrModifiedHandler
         * @desc Handle DOMAttrModified event on panel to respond to Windows 8 Narrator ExpandCollapse pattern
         * @param {event} Event object
         * @memberof jQuery.fn.accessibleMegaMenu
         * @inner
         * @private
         */
        _DOMAttrModifiedHandler = function (event) {
            if (event.originalEvent.attrName === 'aria-expanded'
                    && event.originalEvent.newValue === 'false'
                    && $(event.target).hasClass(this.settings.openClass)) {
                event.preventDefault();
                event.stopPropagation();
                _togglePanel.call(this, event, true);
            }
        };

        /**
         * @name jQuery.fn.accessibleMegaMenu~_focusInHandler
         * @desc Handle focusin event on mega menu item.
         * @param {event} Event object
         * @memberof jQuery.fn.accessibleMegaMenu
         * @inner
         * @private
         */
        _focusInHandler = function (event) {
            clearTimeout(this.focusTimeoutID);
            var target = $(event.target),
                panel = target.closest('.' + this.settings.panelClass);
            target
                .addClass(this.settings.focusClass)
                .on('click.accessible-megamenu', $.proxy(_clickHandler, this));
            this.justFocused = !this.mouseFocused;
            this.mouseFocused = false;
            if (this.panels.not(panel).filter('.' + this.settings.openClass).length) {
                _togglePanel.call(this, event);
            }
        };

        /**
         * @name jQuery.fn.accessibleMegaMenu~_focusOutHandler
         * @desc Handle focusout event on mega menu item.
         * @param {event} Event object
         * @memberof jQuery.fn.accessibleMegaMenu
         * @inner
         * @private
         */
        _focusOutHandler = function (event) {
            this.justFocused = false;
            var that = this,
                target = $(event.target),
                topli = target.closest('.' + this.settings.topNavItemClass),
                keepOpen = false;
            target
                .removeClass(this.settings.focusClass)
                .off('click.accessible-megamenu');

            if (window.cvox) {
                // If ChromeVox is running...
                that.focusTimeoutID = setTimeout(function () {
                    window.cvox.Api.getCurrentNode(function (node) {
                        if (topli.has(node).length) {
                            // and the current node being voiced is in
                            // the mega menu, clearTimeout,
                            // so the panel stays open.
                            clearTimeout(that.focusTimeoutID);
                        } else {
                            that.focusTimeoutID = setTimeout(function (scope, event, hide) {
                                _togglePanel.call(scope, event, hide);
                            }, 275, that, event, true);
                        }
                    });
                }, 25);
            } else {
                that.focusTimeoutID = setTimeout(function () {
                    _togglePanel.call(that, event, true);
                }, 300);
            }
        };

        /**
         * @name jQuery.fn.accessibleMegaMenu~_keyDownHandler
         * @desc Handle keydown event on mega menu.
         * @param {event} Event object
         * @memberof jQuery.fn.accessibleMegaMenu
         * @inner
         * @private
         */
        _keyDownHandler = function (event) {
            var that = (this.constructor === AccessibleMegaMenu) ? this : _getPlugin(this), // determine the AccessibleMegaMenu plugin instance
                settings = that.settings,
                target = $($(this).is('.' + settings.hoverClass + ':tabbable') ? this : event.target), // if the element is hovered the target is this, otherwise, its the focused element
                menu = that.menu,
                topnavitems = that.topnavitems,
                topli = target.closest('.' + settings.topNavItemClass),
                tabbables = menu.find(':tabbable'),
                panel = target.hasClass(settings.panelClass) ? target : target.closest('.' + settings.panelClass),
                panelGroups = panel.find('.' + settings.panelGroupClass),
                currentPanelGroup = target.closest('.' + settings.panelGroupClass),
                next,
                keycode = event.keyCode || event.which,
                start,
                i,
                o,
                label,
                found = false,
                newString = Keyboard.keyMap[event.keyCode] || '',
                regex,
                isTopNavItem = (topli.length === 1 && panel.length === 0);

            if (target.is("input:focus, select:focus, textarea:focus, button:focus")) {
                // if the event target is a form element we should handle keydown normally
                return;
            }

            if (target.is('.' + settings.hoverClass + ':tabbable')) {
                $('html').off('keydown.accessible-megamenu');
            }

            switch (keycode) {
            case Keyboard.ESCAPE:
                _togglePanel.call(that, event, true);
                break;
            case Keyboard.DOWN:
                event.preventDefault();
                if (isTopNavItem) {
                    _togglePanel.call(that, event);
                    found = (topli.find('.' + settings.panelClass + ' :tabbable:first').focus().length === 1);
                } else {
                    found = (tabbables.filter(':gt(' + tabbables.index(target) + '):first').focus().length === 1);
                }

                if (!found && window.opera && opera.toString() === "[object Opera]" && (event.ctrlKey || event.metaKey)) {
                    tabbables = $(':tabbable');
                    i = tabbables.index(target);
                    found = ($(':tabbable:gt(' + $(':tabbable').index(target) + '):first').focus().length === 1);
                }
                break;
            case Keyboard.UP:
                event.preventDefault();
                if (isTopNavItem && target.hasClass(settings.openClass)) {
                    _togglePanel.call(that, event, true);
                    next = topnavitems.filter(':lt(' + topnavitems.index(topli) + '):last');
                    if (next.children('.' + settings.panelClass).length) {
                        found = (next.children()
                            .attr('aria-expanded', 'true')
                            .addClass(settings.openClass)
                            .filter('.' + settings.panelClass)
                            .attr('aria-hidden', 'false')
                            .find(':tabbable:last')
                            .focus() === 1);
                    }
                } else if (!isTopNavItem) {
                    found = (tabbables.filter(':lt(' + tabbables.index(target) + '):last').focus().length === 1);
                }

                if (!found && window.opera && opera.toString() === "[object Opera]" && (event.ctrlKey || event.metaKey)) {
                    tabbables = $(':tabbable');
                    i = tabbables.index(target);
                    found = ($(':tabbable:lt(' + $(':tabbable').index(target) + '):first').focus().length === 1);
                }
                break;
            case Keyboard.RIGHT:
                event.preventDefault();
                if (isTopNavItem) {
                    found = (topnavitems.filter(':gt(' + topnavitems.index(topli) + '):first').find(':tabbable:first').focus().length === 1);
                } else {
                    if (panelGroups.length && currentPanelGroup.length) {
                        // if the current panel contains panel groups, and we are able to focus the first tabbable element of the next panel group
                        found = (panelGroups.filter(':gt(' + panelGroups.index(currentPanelGroup) + '):first').find(':tabbable:first').focus().length === 1);
                    }

                    if (!found) {
                        found = (topli.find(':tabbable:first').focus().length === 1);
                    }
                }
                break;
            case Keyboard.LEFT:
                event.preventDefault();
                if (isTopNavItem) {
                    found = (topnavitems.filter(':lt(' + topnavitems.index(topli) + '):last').find(':tabbable:first').focus().length === 1);
                } else {
                    if (panelGroups.length && currentPanelGroup.length) {
                        // if the current panel contains panel groups, and we are able to focus the first tabbable element of the previous panel group
                        found = (panelGroups.filter(':lt(' + panelGroups.index(currentPanelGroup) + '):last').find(':tabbable:first').focus().length === 1);
                    }

                    if (!found) {
                        found = (topli.find(':tabbable:first').focus().length === 1);
                    }
                }
                break;
            case Keyboard.TAB:
                i = tabbables.index(target);
                if (event.shiftKey && isTopNavItem && target.hasClass(settings.openClass)) {
                    _togglePanel.call(that, event, true);
                    next = topnavitems.filter(':lt(' + topnavitems.index(topli) + '):last');
                    if (next.children('.' + settings.panelClass).length) {
                        found = next.children()
                            .attr('aria-expanded', 'true')
                            .addClass(settings.openClass)
                            .filter('.' + settings.panelClass)
                            .attr('aria-hidden', 'false')
                            .find(':tabbable:last')
                            .focus();
                    }
                } else if (event.shiftKey && i > 0) {
                    found = (tabbables.filter(':lt(' + i + '):last').focus().length === 1);
                } else if (!event.shiftKey && i < tabbables.length - 1) {
                    found = (tabbables.filter(':gt(' + i + '):first').focus().length === 1);
                } else if (window.opera && opera.toString() === "[object Opera]") {
                    tabbables = $(':tabbable');
                    i = tabbables.index(target);
                    if (event.shiftKey) {
                        found = ($(':tabbable:lt(' + $(':tabbable').index(target) + '):last').focus().length === 1);
                    } else {
                        found = ($(':tabbable:gt(' + $(':tabbable').index(target) + '):first').focus().length === 1);
                    }
                }

                if (found) {
                    event.preventDefault();
                }
                break;
            case Keyboard.SPACE:
                if (isTopNavItem) {
                    event.preventDefault();
                    _clickHandler.call(that, event);
                } else {
                    return true;
                }
                break;
            case Keyboard.ENTER:
                return true;
                break;
            default:
                // alphanumeric filter
                clearTimeout(this.keydownTimeoutID);

                keydownSearchString += newString !== keydownSearchString ? newString : '';

                if (keydownSearchString.length === 0) {
                    return;
                }

                this.keydownTimeoutID = setTimeout(function () {
                    keydownSearchString = '';
                }, keydownTimeoutDuration);

                if (isTopNavItem && !target.hasClass(settings.openClass)) {
                    tabbables = tabbables.filter(':not(.' + settings.panelClass + ' :tabbable)');
                } else {
                    tabbables = topli.find(':tabbable');
                }

                if (event.shiftKey) {
                    tabbables = $(tabbables.get()
                        .reverse());
                }

                for (i = 0; i < tabbables.length; i++) {
                    o = tabbables.eq(i);
                    if (o.is(target)) {
                        start = (keydownSearchString.length === 1) ? i + 1 : i;
                        break;
                    }
                }

                regex = new RegExp('^' + keydownSearchString.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&'), 'i');

                for (i = start; i < tabbables.length; i++) {
                    o = tabbables.eq(i);
                    label = $.trim(o.text());
                    if (regex.test(label)) {
                        found = true;
                        o.focus();
                        break;
                    }
                }
                if (!found) {
                    for (i = 0; i < start; i++) {
                        o = tabbables.eq(i);
                        label = $.trim(o.text());
                        if (regex.test(label)) {
                            o.focus();
                            break;
                        }
                    }
                }
                break;
            }
            that.justFocused = false;
        };

        /**
         * @name jQuery.fn.accessibleMegaMenu~_mouseDownHandler
         * @desc Handle mousedown event on mega menu.
         * @param {event} Event object
         * @memberof accessibleMegaMenu
         * @inner
         * @private
         */
        _mouseDownHandler = function (event) {
            if ($(event.target).is(this.settings.panelClass) || $(event.target).closest(":focusable").length) {
                this.mouseFocused = true;
            }
            this.mouseTimeoutID = setTimeout(function () {
                clearTimeout(this.focusTimeoutID);
            }, 1);
        };

        /**
         * @name jQuery.fn.accessibleMegaMenu~_mouseOverHandler
         * @desc Handle mouseover event on mega menu.
         * @param {event} Event object
         * @memberof jQuery.fn.accessibleMegaMenu
         * @inner
         * @private
         */
        _mouseOverHandler = function (event) {
            clearTimeout(this.mouseTimeoutID);
            $(event.target)
                .addClass(this.settings.hoverClass);
            _togglePanel.call(this, event);
            if ($(event.target).is(':tabbable')) {
                $('html').on('keydown.accessible-megamenu', $.proxy(_keyDownHandler, event.target));
            }
        };

        /**
         * @name jQuery.fn.accessibleMegaMenu~_mouseOutHandler
         * @desc Handle mouseout event on mega menu.
         * @param {event} Event object
         * @memberof jQuery.fn.accessibleMegaMenu
         * @inner
         * @private
         */
        _mouseOutHandler = function (event) {
            var that = this;
            $(event.target)
                .removeClass(that.settings.hoverClass);

            that.mouseTimeoutID = setTimeout(function () {
                _togglePanel.call(that, event, true);
            }, 250);
            if ($(event.target).is(':tabbable')) {
                $('html').off('keydown.accessible-megamenu');
            }
        };

        _toggleExpandedEventHandlers = function (hide) {
            var menu = this.menu;
            if (hide) {
                $('html').off('mouseup.outside-accessible-megamenu, touchend.outside-accessible-megamenu, mspointerup.outside-accessible-megamenu,  pointerup.outside-accessible-megamenu');

                menu.find('[aria-expanded].' + this.settings.panelClass).off('DOMAttrModified.accessible-megamenu');
            } else {
                $('html').on('mouseup.outside-accessible-megamenu, touchend.outside-accessible-megamenu, mspointerup.outside-accessible-megamenu,  pointerup.outside-accessible-megamenu', $.proxy(_clickOutsideHandler, this));

                /* Narrator in Windows 8 automatically toggles the aria-expanded property on double tap or click.
                   To respond to the change to collapse the panel, we must add a listener for a DOMAttrModified event. */
                menu.find('[aria-expanded=true].' + this.settings.panelClass).on('DOMAttrModified.accessible-megamenu', $.proxy(_DOMAttrModifiedHandler, this));
            }
        };

        /* public attributes and methods ------------------------- */
        return {
            constructor: AccessibleMegaMenu,

            /**
             * @lends jQuery.fn.accessibleMegaMenu
             * @desc Initializes an instance of the accessibleMegaMenu plugins
             * @memberof jQuery.fn.accessibleMegaMenu
             * @instance
             */
            init: function () {
                var settings = this.settings,
                    nav = $(this.element),
                    menu = nav.children().first(),
                    topnavitems = menu.children();
                this.start(settings, nav, menu, topnavitems);
            },

            start: function(settings, nav, menu, topnavitems) {
                var that = this;
                this.settings = settings;
                this.menu = menu;
                this.topnavitems = topnavitems;

                nav.attr("role", "navigation");
                menu.addClass(settings.menuClass);
                topnavitems.each(function (i, topnavitem) {
                    var topnavitemlink, topnavitempanel;
                    topnavitem = $(topnavitem);
                    topnavitem.addClass(settings.topNavItemClass);
                    topnavitemlink = topnavitem.find(":tabbable:first");
                    topnavitempanel = topnavitem.children(":not(:tabbable):last");
                    _addUniqueId.call(that, topnavitemlink);
                    if (topnavitempanel.length) {
                        _addUniqueId.call(that, topnavitempanel);
                        topnavitemlink.attr({
                            "aria-haspopup": true,
                            "aria-controls": topnavitempanel.attr("id"),
                            "aria-expanded": false
                        });

                        topnavitempanel.attr({
                            "role": "group",
                            "aria-expanded": false,
                            "aria-hidden": true
                        })
                            .addClass(settings.panelClass)
                            .not("[aria-labelledby]")
                            .attr("aria-labelledby", topnavitemlink.attr("id"));
                    }
                });

                this.panels = menu.find("." + settings.panelClass);

                menu.on("focusin.accessible-megamenu", ":focusable, ." + settings.panelClass, $.proxy(_focusInHandler, this))
                    .on("focusout.accessible-megamenu", ":focusable, ." + settings.panelClass, $.proxy(_focusOutHandler, this))
                    .on("keydown.accessible-megamenu", $.proxy(_keyDownHandler, this))
                    .on("mouseover.accessible-megamenu", $.proxy(_mouseOverHandler, this))
                    .on("mouseout.accessible-megamenu", $.proxy(_mouseOutHandler, this))
                    .on("mousedown.accessible-megamenu", $.proxy(_mouseDownHandler, this));

                if (isTouch) {
                    menu.on("touchstart.accessible-megamenu",  $.proxy(_clickHandler, this));
                }

                menu.find("hr").attr("role", "separator");

                if ($(document.activeElement).closest(menu).length) {
                  $(document.activeElement).trigger("focusin.accessible-megamenu");
                }
            },

            /**
             * @desc Get default values
             * @example $(selector).accessibleMegaMenu("getDefaults");
             * @return {object}
             * @memberof jQuery.fn.accessibleMegaMenu
             * @instance
             */
            getDefaults: function () {
                return this._defaults;
            },

            /**
             * @desc Get any option set to plugin using its name (as string)
             * @example $(selector).accessibleMegaMenu("getOption", some_option);
             * @param {string} opt
             * @return {string}
             * @memberof jQuery.fn.accessibleMegaMenu
             * @instance
             */
            getOption: function (opt) {
                return this.settings[opt];
            },

            /**
             * @desc Get all options
             * @example $(selector).accessibleMegaMenu("getAllOptions");
             * @return {object}
             * @memberof jQuery.fn.accessibleMegaMenu
             * @instance
             */
            getAllOptions: function () {
                return this.settings;
            },

            /**
             * @desc Set option
             * @example $(selector).accessibleMegaMenu("setOption", "option_name",  "option_value",  reinitialize);
             * @param {string} opt - Option name
             * @param {string} val - Option value
             * @param {boolean} [reinitialize] - boolean to re-initialize the menu.
             * @memberof jQuery.fn.accessibleMegaMenu
             * @instance
             */
            setOption: function (opt, value, reinitialize) {
                this.settings[opt] = value;
                if (reinitialize) {
                    this.init();
                }
            }
        };
    }());

    /* lightweight plugin wrapper around the constructor,
       to prevent against multiple instantiations */

    /**
     * @class accessibleMegaMenu
     * @memberOf jQuery.fn
     * @classdesc Implements an accessible mega menu as a jQuery plugin.
     * <p>The mega-menu It is modeled after the mega menu on {@link http://adobe.com|adobe.com} but has been simplified for use by others. A brief description of the interaction design choices can be found in a blog post at {@link http://blogs.adobe.com/accessibility/2013/05/adobe-com.html|Mega menu accessibility on adobe.com}.</p>
     * <h3>Keyboard Accessibility</h3>
     * <p>The accessible mega menu supports keyboard interaction modeled after the behavior described in the {@link http://www.w3.org/TR/wai-aria-practices/#menu|WAI-ARIA Menu or Menu bar (widget) design pattern}, however we also try to respect users' general expectations for the behavior of links in a global navigation. To this end, the accessible mega menu implementation permits tab focus on each of the six top-level menu items. When one of the menu items has focus, pressing the Enter key, Spacebar or Down arrow will open the submenu panel, and pressing the Left or Right arrow key will shift focus to the adjacent menu item. Links within the submenu panels are included in the tab order when the panel is open. They can also be navigated with the arrow keys or by typing the first character in the link name, which speeds up keyboard navigation considerably. Pressing the Escape key closes the submenu and restores focus to the parent menu item.</p>
     * <h3>Screen Reader Accessibility</h3>
     * <p>The accessible mega menu models its use of WAI-ARIA Roles, States, and Properties after those described in the {@link http://www.w3.org/TR/wai-aria-practices/#menu|WAI-ARIA Menu or Menu bar (widget) design pattern} with some notable exceptions, so that it behaves better with screen reader user expectations for global navigation. We don't use <code class="prettyprint prettyprinted" style=""><span class="pln">role</span><span class="pun">=</span><span class="str">"menu"</span></code> for the menu container and <code class="prettyprint prettyprinted" style=""><span class="pln">role</span><span class="pun">=</span><span class="str">"menuitem"</span></code> for each of the links therein, because if we do, assistive technology will no longer interpret the links as links, but instead, as menu items, and the links in our global navigation will no longer show up when a screen reader user executes a shortcut command to bring up a list of links in the page.</p>
     * @example <h4>HTML</h4><hr/>
&lt;nav&gt;
    &lt;ul class=&quot;nav-menu&quot;&gt;
        &lt;li class=&quot;nav-item&quot;&gt;
            &lt;a href=&quot;?movie&quot;&gt;Movies&lt;/a&gt;
            &lt;div class=&quot;sub-nav&quot;&gt;
                &lt;ul class=&quot;sub-nav-group&quot;&gt;
                    &lt;li&gt;&lt;a href=&quot;?movie&amp;genre=0&quot;&gt;Action &amp;amp; Adventure&lt;/a&gt;&lt;/li&gt;
                    &lt;li&gt;&lt;a href=&quot;?movie&amp;genre=2&quot;&gt;Children &amp;amp; Family&lt;/a&gt;&lt;/li&gt;
                    &lt;li&gt;&amp;#8230;&lt;/li&gt;
                &lt;/ul&gt;
                &lt;ul class=&quot;sub-nav-group&quot;&gt;
                    &lt;li&gt;&lt;a href=&quot;?movie&amp;genre=7&quot;&gt;Dramas&lt;/a&gt;&lt;/li&gt;
                    &lt;li&gt;&lt;a href=&quot;?movie&amp;genre=9&quot;&gt;Foreign&lt;/a&gt;&lt;/li&gt;
                    &lt;li&gt;&amp;#8230;&lt;/li&gt;
                &lt;/ul&gt;
                &lt;ul class=&quot;sub-nav-group&quot;&gt;
                    &lt;li&gt;&lt;a href=&quot;?movie&amp;genre=14&quot;&gt;Musicals&lt;/a&gt;&lt;/li&gt;
                    &lt;li&gt;&lt;a href=&quot;?movie&amp;genre=15&quot;&gt;Romance&lt;/a&gt;&lt;/li&gt;
                    &lt;li&gt;&amp;#8230;&lt;/li&gt;
                &lt;/ul&gt;
            &lt;/div&gt;
        &lt;/li&gt;
        &lt;li class=&quot;nav-item&quot;&gt;
            &lt;a href=&quot;?tv&quot;&gt;TV Shows&lt;/a&gt;
            &lt;div class=&quot;sub-nav&quot;&gt;
                &lt;ul class=&quot;sub-nav-group&quot;&gt;
                    &lt;li&gt;&lt;a href=&quot;?tv&amp;genre=20&quot;&gt;Classic TV&lt;/a&gt;&lt;/li&gt;
                    &lt;li&gt;&lt;a href=&quot;?tv&amp;genre=21&quot;&gt;Crime TV&lt;/a&gt;&lt;/li&gt;
                    &lt;li&gt;&amp;#8230;&lt;/li&gt;
                &lt;/ul&gt;
                &lt;ul class=&quot;sub-nav-group&quot;&gt;
                    &lt;li&gt;&lt;a href=&quot;?tv&amp;genre=27&quot;&gt;Reality TV&lt;/a&gt;&lt;/li&gt;
                    &lt;li&gt;&lt;a href=&quot;?tv&amp;genre=30&quot;&gt;TV Action&lt;/a&gt;&lt;/li&gt;
                    &lt;li&gt;&amp;#8230;&lt;/li&gt;
                &lt;/ul&gt;
                &lt;ul class=&quot;sub-nav-group&quot;&gt;
                    &lt;li&gt;&lt;a href=&quot;?tv&amp;genre=33&quot;&gt;TV Dramas&lt;/a&gt;&lt;/li&gt;
                    &lt;li&gt;&lt;a href=&quot;?tv&amp;genre=34&quot;&gt;TV Horror&lt;/a&gt;&lt;/li&gt;
                    &lt;li&gt;&amp;#8230;&lt;/li&gt;
                &lt;/ul&gt;
            &lt;/div&gt;
        &lt;/li&gt;
    &lt;/ul&gt;
&lt;/nav&gt;
     * @example <h4>CSS</h4><hr/>
&#47;* Rudimentary mega menu CSS for demonstration *&#47;

&#47;* mega menu list *&#47;
.nav-menu {
    display: block;
    position: relative;
    list-style: none;
    margin: 0;
    padding: 0;
    z-index: 15;
}

&#47;* a top level navigation item in the mega menu *&#47;
.nav-item {
    list-style: none;
    display: inline-block;
    padding: 0;
    margin: 0;
}

&#47;* first descendant link within a top level navigation item *&#47;
.nav-item &gt; a {
    position: relative;
    display: inline-block;
    padding: 0.5em 1em;
    margin: 0 0 -1px 0;
    border: 1px solid transparent;
}

&#47;* focus/open states of first descendant link within a top level
   navigation item *&#47;
.nav-item &gt; a:focus,
.nav-item &gt; a.open {
    border: 1px solid #dedede;
}

&#47;* open state of first descendant link within a top level
   navigation item *&#47;
.nav-item &gt; a.open {
    background-color: #fff;
    border-bottom: none;
    z-index: 1;
}

&#47;* sub-navigation panel *&#47;
.sub-nav {
    position: absolute;
    display: none;
    top: 2.2em;
    margin-top: -1px;
    padding: 0.5em 1em;
    border: 1px solid #dedede;
    background-color: #fff;
}

&#47;* sub-navigation panel open state *&#47;
.sub-nav.open {
    display: block;
}

&#47;* list of items within sub-navigation panel *&#47;
.sub-nav ul {
    display: inline-block;
    vertical-align: top;
    margin: 0 1em 0 0;
    padding: 0;
}

&#47;* list item within sub-navigation panel *&#47;
.sub-nav li {
    display: block;
    list-style-type: none;
    margin: 0;
    padding: 0;
}
     * @example <h4>JavaScript</h4><hr/>
&lt;!-- include jquery --&gt;
&lt;script src=&quot;http://code.jquery.com/jquery-1.10.1.min.js&quot;&gt;&lt;/script&gt;

&lt;!-- include the jquery-accessibleMegaMenu plugin script --&gt;
&lt;script src=&quot;js/jquery-accessibleMegaMenu.js&quot;&gt;&lt;/script&gt;

&lt;!-- initialize a selector as an accessibleMegaMenu --&gt;
&lt;script&gt;
    $(&quot;nav:first&quot;).accessibleMegaMenu({
        &#47;* prefix for generated unique id attributes, which are required to indicate aria-owns, aria-controls and aria-labelledby *&#47;
        uuidPrefix: &quot;accessible-megamenu&quot;,

        &#47;* css class used to define the megamenu styling *&#47;
        menuClass: &quot;nav-menu&quot;,

        &#47;* css class for a top-level navigation item in the megamenu *&#47;
        topNavItemClass: &quot;nav-item&quot;,

        &#47;* css class for a megamenu panel *&#47;
        panelClass: &quot;sub-nav&quot;,

        &#47;* css class for a group of items within a megamenu panel *&#47;
        panelGroupClass: &quot;sub-nav-group&quot;,

        &#47;* css class for the hover state *&#47;
        hoverClass: &quot;hover&quot;,

        &#47;* css class for the focus state *&#47;
        focusClass: &quot;focus&quot;,

        &#47;* css class for the open state *&#47;
        openClass: &quot;open&quot;
    });
&lt;/script&gt;
     * @param {object} [options] Mega Menu options
     * @param {string} [options.uuidPrefix=accessible-megamenu] - Prefix for generated unique id attributes, which are required to indicate aria-owns, aria-controls and aria-labelledby
     * @param {string} [options.menuClass=accessible-megamenu] - CSS class used to define the megamenu styling
     * @param {string} [options.topNavItemClass=accessible-megamenu-top-nav-item] - CSS class for a top-level navigation item in the megamenu
     * @param {string} [options.panelClass=accessible-megamenu-panel] - CSS class for a megamenu panel
     * @param {string} [options.panelGroupClass=accessible-megamenu-panel-group] - CSS class for a group of items within a megamenu panel
     * @param {string} [options.hoverClass=hover] - CSS class for the hover state
     * @param {string} [options.focusClass=focus] - CSS class for the focus state
     * @param {string} [options.openClass=open] - CSS class for the open state
     */
    $.fn[pluginName] = function (options) {
        return this.each(function () {
            if (!$.data(this, "plugin_" + pluginName)) {
                $.data(this, "plugin_" + pluginName, new $.fn[pluginName].AccessibleMegaMenu(this, options));
            }
        });
    };

    $.fn[pluginName].AccessibleMegaMenu = AccessibleMegaMenu;

    /* :focusable and :tabbable selectors from
       https://raw.github.com/jquery/jquery-ui/master/ui/jquery.ui.core.js */

    /**
     * @private
     */
    function visible(element) {
        return $.expr.filters.visible(element) && !$(element).parents().addBack().filter(function () {
            return $.css(this, "visibility") === "hidden";
        }).length;
    }

    /**
     * @private
     */
    function focusable(element, isTabIndexNotNaN) {
        var map, mapName, img,
            nodeName = element.nodeName.toLowerCase();
        if ("area" === nodeName) {
            map = element.parentNode;
            mapName = map.name;
            if (!element.href || !mapName || map.nodeName.toLowerCase() !== "map") {
                return false;
            }
            img = $("img[usemap=#" + mapName + "]")[0];
            return !!img && visible(img);
        }
        return (/input|select|textarea|button|object/.test(nodeName) ? !element.disabled :
                "a" === nodeName ?
                        element.href || isTabIndexNotNaN :
                        isTabIndexNotNaN) &&
                            // the element and all of its ancestors must be visible
                            visible(element);
    }

    $.extend($.expr[":"], {
        data: $.expr.createPseudo ? $.expr.createPseudo(function (dataName) {
            return function (elem) {
                return !!$.data(elem, dataName);
            };
        }) : // support: jQuery <1.8
                function (elem, i, match) {
                    return !!$.data(elem, match[3]);
                },

        focusable: function (element) {
            return focusable(element, !isNaN($.attr(element, "tabindex")));
        },

        tabbable: function (element) {
            var tabIndex = $.attr(element, "tabindex"),
                isTabIndexNaN = isNaN(tabIndex);
            return (isTabIndexNaN || tabIndex >= 0) && focusable(element, !isTabIndexNaN);
        }
    });
}(jQuery, window, document));
;
/* NUGET: BEGIN LICENSE TEXT
 *
 * Microsoft grants you the right to use these script files for the sole
 * purpose of either: (i) interacting through your browser with the Microsoft
 * website or online service, subject to the applicable licensing or use
 * terms; or (ii) using the files as included with a Microsoft product subject
 * to that product's license terms. Microsoft reserves all other rights to the
 * files not expressly granted by Microsoft, whether by implication, estoppel
 * or otherwise. Insofar as a script file is dual licensed under GPL,
 * Microsoft neither took the code under GPL nor distributes it thereunder but
 * under the terms set out in this paragraph. All notices and licenses
 * below are for informational purposes only.
 *
 * NUGET: END LICENSE TEXT */
/*! jQuery Validation Plugin - v1.11.1 - 3/22/2013\n* https://github.com/jzaefferer/jquery-validation
* Copyright (c) 2013 Jörn Zaefferer; Licensed MIT */(function(t){t.extend(t.fn,{validate:function(e){if(!this.length)return e&&e.debug&&window.console&&console.warn("Nothing selected, can't validate, returning nothing."),void 0;var i=t.data(this[0],"validator");return i?i:(this.attr("novalidate","novalidate"),i=new t.validator(e,this[0]),t.data(this[0],"validator",i),i.settings.onsubmit&&(this.validateDelegate(":submit","click",function(e){i.settings.submitHandler&&(i.submitButton=e.target),t(e.target).hasClass("cancel")&&(i.cancelSubmit=!0),void 0!==t(e.target).attr("formnovalidate")&&(i.cancelSubmit=!0)}),this.submit(function(e){function s(){var s;return i.settings.submitHandler?(i.submitButton&&(s=t("<input type='hidden'/>").attr("name",i.submitButton.name).val(t(i.submitButton).val()).appendTo(i.currentForm)),i.settings.submitHandler.call(i,i.currentForm,e),i.submitButton&&s.remove(),!1):!0}return i.settings.debug&&e.preventDefault(),i.cancelSubmit?(i.cancelSubmit=!1,s()):i.form()?i.pendingRequest?(i.formSubmitted=!0,!1):s():(i.focusInvalid(),!1)})),i)},valid:function(){if(t(this[0]).is("form"))return this.validate().form();var e=!0,i=t(this[0].form).validate();return this.each(function(){e=e&&i.element(this)}),e},removeAttrs:function(e){var i={},s=this;return t.each(e.split(/\s/),function(t,e){i[e]=s.attr(e),s.removeAttr(e)}),i},rules:function(e,i){var s=this[0];if(e){var r=t.data(s.form,"validator").settings,n=r.rules,a=t.validator.staticRules(s);switch(e){case"add":t.extend(a,t.validator.normalizeRule(i)),delete a.messages,n[s.name]=a,i.messages&&(r.messages[s.name]=t.extend(r.messages[s.name],i.messages));break;case"remove":if(!i)return delete n[s.name],a;var u={};return t.each(i.split(/\s/),function(t,e){u[e]=a[e],delete a[e]}),u}}var o=t.validator.normalizeRules(t.extend({},t.validator.classRules(s),t.validator.attributeRules(s),t.validator.dataRules(s),t.validator.staticRules(s)),s);if(o.required){var l=o.required;delete o.required,o=t.extend({required:l},o)}return o}}),t.extend(t.expr[":"],{blank:function(e){return!t.trim(""+t(e).val())},filled:function(e){return!!t.trim(""+t(e).val())},unchecked:function(e){return!t(e).prop("checked")}}),t.validator=function(e,i){this.settings=t.extend(!0,{},t.validator.defaults,e),this.currentForm=i,this.init()},t.validator.format=function(e,i){return 1===arguments.length?function(){var i=t.makeArray(arguments);return i.unshift(e),t.validator.format.apply(this,i)}:(arguments.length>2&&i.constructor!==Array&&(i=t.makeArray(arguments).slice(1)),i.constructor!==Array&&(i=[i]),t.each(i,function(t,i){e=e.replace(RegExp("\\{"+t+"\\}","g"),function(){return i})}),e)},t.extend(t.validator,{defaults:{messages:{},groups:{},rules:{},errorClass:"error",validClass:"valid",errorElement:"label",focusInvalid:!0,errorContainer:t([]),errorLabelContainer:t([]),onsubmit:!0,ignore:":hidden",ignoreTitle:!1,onfocusin:function(t){this.lastActive=t,this.settings.focusCleanup&&!this.blockFocusCleanup&&(this.settings.unhighlight&&this.settings.unhighlight.call(this,t,this.settings.errorClass,this.settings.validClass),this.addWrapper(this.errorsFor(t)).hide())},onfocusout:function(t){this.checkable(t)||!(t.name in this.submitted)&&this.optional(t)||this.element(t)},onkeyup:function(t,e){(9!==e.which||""!==this.elementValue(t))&&(t.name in this.submitted||t===this.lastElement)&&this.element(t)},onclick:function(t){t.name in this.submitted?this.element(t):t.parentNode.name in this.submitted&&this.element(t.parentNode)},highlight:function(e,i,s){"radio"===e.type?this.findByName(e.name).addClass(i).removeClass(s):t(e).addClass(i).removeClass(s)},unhighlight:function(e,i,s){"radio"===e.type?this.findByName(e.name).removeClass(i).addClass(s):t(e).removeClass(i).addClass(s)}},setDefaults:function(e){t.extend(t.validator.defaults,e)},messages:{required:"This field is required.",remote:"Please fix this field.",email:"Please enter a valid email address.",url:"Please enter a valid URL.",date:"Please enter a valid date.",dateISO:"Please enter a valid date (ISO).",number:"Please enter a valid number.",digits:"Please enter only digits.",creditcard:"Please enter a valid credit card number.",equalTo:"Please enter the same value again.",maxlength:t.validator.format("Please enter no more than {0} characters."),minlength:t.validator.format("Please enter at least {0} characters."),rangelength:t.validator.format("Please enter a value between {0} and {1} characters long."),range:t.validator.format("Please enter a value between {0} and {1}."),max:t.validator.format("Please enter a value less than or equal to {0}."),min:t.validator.format("Please enter a value greater than or equal to {0}.")},autoCreateRanges:!1,prototype:{init:function(){function e(e){var i=t.data(this[0].form,"validator"),s="on"+e.type.replace(/^validate/,"");i.settings[s]&&i.settings[s].call(i,this[0],e)}this.labelContainer=t(this.settings.errorLabelContainer),this.errorContext=this.labelContainer.length&&this.labelContainer||t(this.currentForm),this.containers=t(this.settings.errorContainer).add(this.settings.errorLabelContainer),this.submitted={},this.valueCache={},this.pendingRequest=0,this.pending={},this.invalid={},this.reset();var i=this.groups={};t.each(this.settings.groups,function(e,s){"string"==typeof s&&(s=s.split(/\s/)),t.each(s,function(t,s){i[s]=e})});var s=this.settings.rules;t.each(s,function(e,i){s[e]=t.validator.normalizeRule(i)}),t(this.currentForm).validateDelegate(":text, [type='password'], [type='file'], select, textarea, [type='number'], [type='search'] ,[type='tel'], [type='url'], [type='email'], [type='datetime'], [type='date'], [type='month'], [type='week'], [type='time'], [type='datetime-local'], [type='range'], [type='color'] ","focusin focusout keyup",e).validateDelegate("[type='radio'], [type='checkbox'], select, option","click",e),this.settings.invalidHandler&&t(this.currentForm).bind("invalid-form.validate",this.settings.invalidHandler)},form:function(){return this.checkForm(),t.extend(this.submitted,this.errorMap),this.invalid=t.extend({},this.errorMap),this.valid()||t(this.currentForm).triggerHandler("invalid-form",[this]),this.showErrors(),this.valid()},checkForm:function(){this.prepareForm();for(var t=0,e=this.currentElements=this.elements();e[t];t++)this.check(e[t]);return this.valid()},element:function(e){e=this.validationTargetFor(this.clean(e)),this.lastElement=e,this.prepareElement(e),this.currentElements=t(e);var i=this.check(e)!==!1;return i?delete this.invalid[e.name]:this.invalid[e.name]=!0,this.numberOfInvalids()||(this.toHide=this.toHide.add(this.containers)),this.showErrors(),i},showErrors:function(e){if(e){t.extend(this.errorMap,e),this.errorList=[];for(var i in e)this.errorList.push({message:e[i],element:this.findByName(i)[0]});this.successList=t.grep(this.successList,function(t){return!(t.name in e)})}this.settings.showErrors?this.settings.showErrors.call(this,this.errorMap,this.errorList):this.defaultShowErrors()},resetForm:function(){t.fn.resetForm&&t(this.currentForm).resetForm(),this.submitted={},this.lastElement=null,this.prepareForm(),this.hideErrors(),this.elements().removeClass(this.settings.errorClass).removeData("previousValue")},numberOfInvalids:function(){return this.objectLength(this.invalid)},objectLength:function(t){var e=0;for(var i in t)e++;return e},hideErrors:function(){this.addWrapper(this.toHide).hide()},valid:function(){return 0===this.size()},size:function(){return this.errorList.length},focusInvalid:function(){if(this.settings.focusInvalid)try{t(this.findLastActive()||this.errorList.length&&this.errorList[0].element||[]).filter(":visible").focus().trigger("focusin")}catch(e){}},findLastActive:function(){var e=this.lastActive;return e&&1===t.grep(this.errorList,function(t){return t.element.name===e.name}).length&&e},elements:function(){var e=this,i={};return t(this.currentForm).find("input, select, textarea").not(":submit, :reset, :image, [disabled]").not(this.settings.ignore).filter(function(){return!this.name&&e.settings.debug&&window.console&&console.error("%o has no name assigned",this),this.name in i||!e.objectLength(t(this).rules())?!1:(i[this.name]=!0,!0)})},clean:function(e){return t(e)[0]},errors:function(){var e=this.settings.errorClass.replace(" ",".");return t(this.settings.errorElement+"."+e,this.errorContext)},reset:function(){this.successList=[],this.errorList=[],this.errorMap={},this.toShow=t([]),this.toHide=t([]),this.currentElements=t([])},prepareForm:function(){this.reset(),this.toHide=this.errors().add(this.containers)},prepareElement:function(t){this.reset(),this.toHide=this.errorsFor(t)},elementValue:function(e){var i=t(e).attr("type"),s=t(e).val();return"radio"===i||"checkbox"===i?t("input[name='"+t(e).attr("name")+"']:checked").val():"string"==typeof s?s.replace(/\r/g,""):s},check:function(e){e=this.validationTargetFor(this.clean(e));var i,s=t(e).rules(),r=!1,n=this.elementValue(e);for(var a in s){var u={method:a,parameters:s[a]};try{if(i=t.validator.methods[a].call(this,n,e,u.parameters),"dependency-mismatch"===i){r=!0;continue}if(r=!1,"pending"===i)return this.toHide=this.toHide.not(this.errorsFor(e)),void 0;if(!i)return this.formatAndAdd(e,u),!1}catch(o){throw this.settings.debug&&window.console&&console.log("Exception occurred when checking element "+e.id+", check the '"+u.method+"' method.",o),o}}return r?void 0:(this.objectLength(s)&&this.successList.push(e),!0)},customDataMessage:function(e,i){return t(e).data("msg-"+i.toLowerCase())||e.attributes&&t(e).attr("data-msg-"+i.toLowerCase())},customMessage:function(t,e){var i=this.settings.messages[t];return i&&(i.constructor===String?i:i[e])},findDefined:function(){for(var t=0;arguments.length>t;t++)if(void 0!==arguments[t])return arguments[t];return void 0},defaultMessage:function(e,i){return this.findDefined(this.customMessage(e.name,i),this.customDataMessage(e,i),!this.settings.ignoreTitle&&e.title||void 0,t.validator.messages[i],"<strong>Warning: No message defined for "+e.name+"</strong>")},formatAndAdd:function(e,i){var s=this.defaultMessage(e,i.method),r=/\$?\{(\d+)\}/g;"function"==typeof s?s=s.call(this,i.parameters,e):r.test(s)&&(s=t.validator.format(s.replace(r,"{$1}"),i.parameters)),this.errorList.push({message:s,element:e}),this.errorMap[e.name]=s,this.submitted[e.name]=s},addWrapper:function(t){return this.settings.wrapper&&(t=t.add(t.parent(this.settings.wrapper))),t},defaultShowErrors:function(){var t,e;for(t=0;this.errorList[t];t++){var i=this.errorList[t];this.settings.highlight&&this.settings.highlight.call(this,i.element,this.settings.errorClass,this.settings.validClass),this.showLabel(i.element,i.message)}if(this.errorList.length&&(this.toShow=this.toShow.add(this.containers)),this.settings.success)for(t=0;this.successList[t];t++)this.showLabel(this.successList[t]);if(this.settings.unhighlight)for(t=0,e=this.validElements();e[t];t++)this.settings.unhighlight.call(this,e[t],this.settings.errorClass,this.settings.validClass);this.toHide=this.toHide.not(this.toShow),this.hideErrors(),this.addWrapper(this.toShow).show()},validElements:function(){return this.currentElements.not(this.invalidElements())},invalidElements:function(){return t(this.errorList).map(function(){return this.element})},showLabel:function(e,i){var s=this.errorsFor(e);s.length?(s.removeClass(this.settings.validClass).addClass(this.settings.errorClass),s.html(i)):(s=t("<"+this.settings.errorElement+">").attr("for",this.idOrName(e)).addClass(this.settings.errorClass).html(i||""),this.settings.wrapper&&(s=s.hide().show().wrap("<"+this.settings.wrapper+"/>").parent()),this.labelContainer.append(s).length||(this.settings.errorPlacement?this.settings.errorPlacement(s,t(e)):s.insertAfter(e))),!i&&this.settings.success&&(s.text(""),"string"==typeof this.settings.success?s.addClass(this.settings.success):this.settings.success(s,e)),this.toShow=this.toShow.add(s)},errorsFor:function(e){var i=this.idOrName(e);return this.errors().filter(function(){return t(this).attr("for")===i})},idOrName:function(t){return this.groups[t.name]||(this.checkable(t)?t.name:t.id||t.name)},validationTargetFor:function(t){return this.checkable(t)&&(t=this.findByName(t.name).not(this.settings.ignore)[0]),t},checkable:function(t){return/radio|checkbox/i.test(t.type)},findByName:function(e){return t(this.currentForm).find("[name='"+e+"']")},getLength:function(e,i){switch(i.nodeName.toLowerCase()){case"select":return t("option:selected",i).length;case"input":if(this.checkable(i))return this.findByName(i.name).filter(":checked").length}return e.length},depend:function(t,e){return this.dependTypes[typeof t]?this.dependTypes[typeof t](t,e):!0},dependTypes:{"boolean":function(t){return t},string:function(e,i){return!!t(e,i.form).length},"function":function(t,e){return t(e)}},optional:function(e){var i=this.elementValue(e);return!t.validator.methods.required.call(this,i,e)&&"dependency-mismatch"},startRequest:function(t){this.pending[t.name]||(this.pendingRequest++,this.pending[t.name]=!0)},stopRequest:function(e,i){this.pendingRequest--,0>this.pendingRequest&&(this.pendingRequest=0),delete this.pending[e.name],i&&0===this.pendingRequest&&this.formSubmitted&&this.form()?(t(this.currentForm).submit(),this.formSubmitted=!1):!i&&0===this.pendingRequest&&this.formSubmitted&&(t(this.currentForm).triggerHandler("invalid-form",[this]),this.formSubmitted=!1)},previousValue:function(e){return t.data(e,"previousValue")||t.data(e,"previousValue",{old:null,valid:!0,message:this.defaultMessage(e,"remote")})}},classRuleSettings:{required:{required:!0},email:{email:!0},url:{url:!0},date:{date:!0},dateISO:{dateISO:!0},number:{number:!0},digits:{digits:!0},creditcard:{creditcard:!0}},addClassRules:function(e,i){e.constructor===String?this.classRuleSettings[e]=i:t.extend(this.classRuleSettings,e)},classRules:function(e){var i={},s=t(e).attr("class");return s&&t.each(s.split(" "),function(){this in t.validator.classRuleSettings&&t.extend(i,t.validator.classRuleSettings[this])}),i},attributeRules:function(e){var i={},s=t(e),r=s[0].getAttribute("type");for(var n in t.validator.methods){var a;"required"===n?(a=s.get(0).getAttribute(n),""===a&&(a=!0),a=!!a):a=s.attr(n),/min|max/.test(n)&&(null===r||/number|range|text/.test(r))&&(a=Number(a)),a?i[n]=a:r===n&&"range"!==r&&(i[n]=!0)}return i.maxlength&&/-1|2147483647|524288/.test(i.maxlength)&&delete i.maxlength,i},dataRules:function(e){var i,s,r={},n=t(e);for(i in t.validator.methods)s=n.data("rule-"+i.toLowerCase()),void 0!==s&&(r[i]=s);return r},staticRules:function(e){var i={},s=t.data(e.form,"validator");return s.settings.rules&&(i=t.validator.normalizeRule(s.settings.rules[e.name])||{}),i},normalizeRules:function(e,i){return t.each(e,function(s,r){if(r===!1)return delete e[s],void 0;if(r.param||r.depends){var n=!0;switch(typeof r.depends){case"string":n=!!t(r.depends,i.form).length;break;case"function":n=r.depends.call(i,i)}n?e[s]=void 0!==r.param?r.param:!0:delete e[s]}}),t.each(e,function(s,r){e[s]=t.isFunction(r)?r(i):r}),t.each(["minlength","maxlength"],function(){e[this]&&(e[this]=Number(e[this]))}),t.each(["rangelength","range"],function(){var i;e[this]&&(t.isArray(e[this])?e[this]=[Number(e[this][0]),Number(e[this][1])]:"string"==typeof e[this]&&(i=e[this].split(/[\s,]+/),e[this]=[Number(i[0]),Number(i[1])]))}),t.validator.autoCreateRanges&&(e.min&&e.max&&(e.range=[e.min,e.max],delete e.min,delete e.max),e.minlength&&e.maxlength&&(e.rangelength=[e.minlength,e.maxlength],delete e.minlength,delete e.maxlength)),e},normalizeRule:function(e){if("string"==typeof e){var i={};t.each(e.split(/\s/),function(){i[this]=!0}),e=i}return e},addMethod:function(e,i,s){t.validator.methods[e]=i,t.validator.messages[e]=void 0!==s?s:t.validator.messages[e],3>i.length&&t.validator.addClassRules(e,t.validator.normalizeRule(e))},methods:{required:function(e,i,s){if(!this.depend(s,i))return"dependency-mismatch";if("select"===i.nodeName.toLowerCase()){var r=t(i).val();return r&&r.length>0}return this.checkable(i)?this.getLength(e,i)>0:t.trim(e).length>0},email:function(t,e){return this.optional(e)||/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(t)},url:function(t,e){return this.optional(e)||/^(https?|s?ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(t)},date:function(t,e){return this.optional(e)||!/Invalid|NaN/.test(""+new Date(t))},dateISO:function(t,e){return this.optional(e)||/^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/.test(t)},number:function(t,e){return this.optional(e)||/^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(t)},digits:function(t,e){return this.optional(e)||/^\d+$/.test(t)},creditcard:function(t,e){if(this.optional(e))return"dependency-mismatch";if(/[^0-9 \-]+/.test(t))return!1;var i=0,s=0,r=!1;t=t.replace(/\D/g,"");for(var n=t.length-1;n>=0;n--){var a=t.charAt(n);s=parseInt(a,10),r&&(s*=2)>9&&(s-=9),i+=s,r=!r}return 0===i%10},minlength:function(e,i,s){var r=t.isArray(e)?e.length:this.getLength(t.trim(e),i);return this.optional(i)||r>=s},maxlength:function(e,i,s){var r=t.isArray(e)?e.length:this.getLength(t.trim(e),i);return this.optional(i)||s>=r},rangelength:function(e,i,s){var r=t.isArray(e)?e.length:this.getLength(t.trim(e),i);return this.optional(i)||r>=s[0]&&s[1]>=r},min:function(t,e,i){return this.optional(e)||t>=i},max:function(t,e,i){return this.optional(e)||i>=t},range:function(t,e,i){return this.optional(e)||t>=i[0]&&i[1]>=t},equalTo:function(e,i,s){var r=t(s);return this.settings.onfocusout&&r.unbind(".validate-equalTo").bind("blur.validate-equalTo",function(){t(i).valid()}),e===r.val()},remote:function(e,i,s){if(this.optional(i))return"dependency-mismatch";var r=this.previousValue(i);if(this.settings.messages[i.name]||(this.settings.messages[i.name]={}),r.originalMessage=this.settings.messages[i.name].remote,this.settings.messages[i.name].remote=r.message,s="string"==typeof s&&{url:s}||s,r.old===e)return r.valid;r.old=e;var n=this;this.startRequest(i);var a={};return a[i.name]=e,t.ajax(t.extend(!0,{url:s,mode:"abort",port:"validate"+i.name,dataType:"json",data:a,success:function(s){n.settings.messages[i.name].remote=r.originalMessage;var a=s===!0||"true"===s;if(a){var u=n.formSubmitted;n.prepareElement(i),n.formSubmitted=u,n.successList.push(i),delete n.invalid[i.name],n.showErrors()}else{var o={},l=s||n.defaultMessage(i,"remote");o[i.name]=r.message=t.isFunction(l)?l(e):l,n.invalid[i.name]=!0,n.showErrors(o)}r.valid=a,n.stopRequest(i,a)}},s)),"pending"}}}),t.format=t.validator.format})(jQuery),function(t){var e={};if(t.ajaxPrefilter)t.ajaxPrefilter(function(t,i,s){var r=t.port;"abort"===t.mode&&(e[r]&&e[r].abort(),e[r]=s)});else{var i=t.ajax;t.ajax=function(s){var r=("mode"in s?s:t.ajaxSettings).mode,n=("port"in s?s:t.ajaxSettings).port;return"abort"===r?(e[n]&&e[n].abort(),e[n]=i.apply(this,arguments),e[n]):i.apply(this,arguments)}}}(jQuery),function(t){t.extend(t.fn,{validateDelegate:function(e,i,s){return this.bind(i,function(i){var r=t(i.target);return r.is(e)?s.apply(r,arguments):void 0})}})}(jQuery);;
(function defineMustache(global,factory){if(typeof exports==="object"&&exports&&typeof exports.nodeName!=="string"){factory(exports)}else if(typeof define==="function"&&define.amd){define(["exports"],factory)}else{global.Mustache={};factory(global.Mustache)}})(this,function mustacheFactory(mustache){var objectToString=Object.prototype.toString;var isArray=Array.isArray||function isArrayPolyfill(object){return objectToString.call(object)==="[object Array]"};function isFunction(object){return typeof object==="function"}function typeStr(obj){return isArray(obj)?"array":typeof obj}function escapeRegExp(string){return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function hasProperty(obj,propName){return obj!=null&&typeof obj==="object"&&propName in obj}var regExpTest=RegExp.prototype.test;function testRegExp(re,string){return regExpTest.call(re,string)}var nonSpaceRe=/\S/;function isWhitespace(string){return!testRegExp(nonSpaceRe,string)}var entityMap={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};function escapeHtml(string){return String(string).replace(/[&<>"'`=\/]/g,function fromEntityMap(s){return entityMap[s]})}var whiteRe=/\s*/;var spaceRe=/\s+/;var equalsRe=/\s*=/;var curlyRe=/\s*\}/;var tagRe=/#|\^|\/|>|\{|&|=|!/;function parseTemplate(template,tags){if(!template)return[];var sections=[];var tokens=[];var spaces=[];var hasTag=false;var nonSpace=false;function stripSpace(){if(hasTag&&!nonSpace){while(spaces.length)delete tokens[spaces.pop()]}else{spaces=[]}hasTag=false;nonSpace=false}var openingTagRe,closingTagRe,closingCurlyRe;function compileTags(tagsToCompile){if(typeof tagsToCompile==="string")tagsToCompile=tagsToCompile.split(spaceRe,2);if(!isArray(tagsToCompile)||tagsToCompile.length!==2)throw new Error("Invalid tags: "+tagsToCompile);openingTagRe=new RegExp(escapeRegExp(tagsToCompile[0])+"\\s*");closingTagRe=new RegExp("\\s*"+escapeRegExp(tagsToCompile[1]));closingCurlyRe=new RegExp("\\s*"+escapeRegExp("}"+tagsToCompile[1]))}compileTags(tags||mustache.tags);var scanner=new Scanner(template);var start,type,value,chr,token,openSection;while(!scanner.eos()){start=scanner.pos;value=scanner.scanUntil(openingTagRe);if(value){for(var i=0,valueLength=value.length;i<valueLength;++i){chr=value.charAt(i);if(isWhitespace(chr)){spaces.push(tokens.length)}else{nonSpace=true}tokens.push(["text",chr,start,start+1]);start+=1;if(chr==="\n")stripSpace()}}if(!scanner.scan(openingTagRe))break;hasTag=true;type=scanner.scan(tagRe)||"name";scanner.scan(whiteRe);if(type==="="){value=scanner.scanUntil(equalsRe);scanner.scan(equalsRe);scanner.scanUntil(closingTagRe)}else if(type==="{"){value=scanner.scanUntil(closingCurlyRe);scanner.scan(curlyRe);scanner.scanUntil(closingTagRe);type="&"}else{value=scanner.scanUntil(closingTagRe)}if(!scanner.scan(closingTagRe))throw new Error("Unclosed tag at "+scanner.pos);token=[type,value,start,scanner.pos];tokens.push(token);if(type==="#"||type==="^"){sections.push(token)}else if(type==="/"){openSection=sections.pop();if(!openSection)throw new Error('Unopened section "'+value+'" at '+start);if(openSection[1]!==value)throw new Error('Unclosed section "'+openSection[1]+'" at '+start)}else if(type==="name"||type==="{"||type==="&"){nonSpace=true}else if(type==="="){compileTags(value)}}openSection=sections.pop();if(openSection)throw new Error('Unclosed section "'+openSection[1]+'" at '+scanner.pos);return nestTokens(squashTokens(tokens))}function squashTokens(tokens){var squashedTokens=[];var token,lastToken;for(var i=0,numTokens=tokens.length;i<numTokens;++i){token=tokens[i];if(token){if(token[0]==="text"&&lastToken&&lastToken[0]==="text"){lastToken[1]+=token[1];lastToken[3]=token[3]}else{squashedTokens.push(token);lastToken=token}}}return squashedTokens}function nestTokens(tokens){var nestedTokens=[];var collector=nestedTokens;var sections=[];var token,section;for(var i=0,numTokens=tokens.length;i<numTokens;++i){token=tokens[i];switch(token[0]){case"#":case"^":collector.push(token);sections.push(token);collector=token[4]=[];break;case"/":section=sections.pop();section[5]=token[2];collector=sections.length>0?sections[sections.length-1][4]:nestedTokens;break;default:collector.push(token)}}return nestedTokens}function Scanner(string){this.string=string;this.tail=string;this.pos=0}Scanner.prototype.eos=function eos(){return this.tail===""};Scanner.prototype.scan=function scan(re){var match=this.tail.match(re);if(!match||match.index!==0)return"";var string=match[0];this.tail=this.tail.substring(string.length);this.pos+=string.length;return string};Scanner.prototype.scanUntil=function scanUntil(re){var index=this.tail.search(re),match;switch(index){case-1:match=this.tail;this.tail="";break;case 0:match="";break;default:match=this.tail.substring(0,index);this.tail=this.tail.substring(index)}this.pos+=match.length;return match};function Context(view,parentContext){this.view=view;this.cache={".":this.view};this.parent=parentContext}Context.prototype.push=function push(view){return new Context(view,this)};Context.prototype.lookup=function lookup(name){var cache=this.cache;var value;if(cache.hasOwnProperty(name)){value=cache[name]}else{var context=this,names,index,lookupHit=false;while(context){if(name.indexOf(".")>0){value=context.view;names=name.split(".");index=0;while(value!=null&&index<names.length){if(index===names.length-1)lookupHit=hasProperty(value,names[index]);value=value[names[index++]]}}else{value=context.view[name];lookupHit=hasProperty(context.view,name)}if(lookupHit)break;context=context.parent}cache[name]=value}if(isFunction(value))value=value.call(this.view);return value};function Writer(){this.cache={}}Writer.prototype.clearCache=function clearCache(){this.cache={}};Writer.prototype.parse=function parse(template,tags){var cache=this.cache;var tokens=cache[template];if(tokens==null)tokens=cache[template]=parseTemplate(template,tags);return tokens};Writer.prototype.render=function render(template,view,partials){var tokens=this.parse(template);var context=view instanceof Context?view:new Context(view);return this.renderTokens(tokens,context,partials,template)};Writer.prototype.renderTokens=function renderTokens(tokens,context,partials,originalTemplate){var buffer="";var token,symbol,value;for(var i=0,numTokens=tokens.length;i<numTokens;++i){value=undefined;token=tokens[i];symbol=token[0];if(symbol==="#")value=this.renderSection(token,context,partials,originalTemplate);else if(symbol==="^")value=this.renderInverted(token,context,partials,originalTemplate);else if(symbol===">")value=this.renderPartial(token,context,partials,originalTemplate);else if(symbol==="&")value=this.unescapedValue(token,context);else if(symbol==="name")value=this.escapedValue(token,context);else if(symbol==="text")value=this.rawValue(token);if(value!==undefined)buffer+=value}return buffer};Writer.prototype.renderSection=function renderSection(token,context,partials,originalTemplate){var self=this;var buffer="";var value=context.lookup(token[1]);function subRender(template){return self.render(template,context,partials)}if(!value)return;if(isArray(value)){for(var j=0,valueLength=value.length;j<valueLength;++j){buffer+=this.renderTokens(token[4],context.push(value[j]),partials,originalTemplate)}}else if(typeof value==="object"||typeof value==="string"||typeof value==="number"){buffer+=this.renderTokens(token[4],context.push(value),partials,originalTemplate)}else if(isFunction(value)){if(typeof originalTemplate!=="string")throw new Error("Cannot use higher-order sections without the original template");value=value.call(context.view,originalTemplate.slice(token[3],token[5]),subRender);if(value!=null)buffer+=value}else{buffer+=this.renderTokens(token[4],context,partials,originalTemplate)}return buffer};Writer.prototype.renderInverted=function renderInverted(token,context,partials,originalTemplate){var value=context.lookup(token[1]);if(!value||isArray(value)&&value.length===0)return this.renderTokens(token[4],context,partials,originalTemplate)};Writer.prototype.renderPartial=function renderPartial(token,context,partials){if(!partials)return;var value=isFunction(partials)?partials(token[1]):partials[token[1]];if(value!=null)return this.renderTokens(this.parse(value),context,partials,value)};Writer.prototype.unescapedValue=function unescapedValue(token,context){var value=context.lookup(token[1]);if(value!=null)return value};Writer.prototype.escapedValue=function escapedValue(token,context){var value=context.lookup(token[1]);if(value!=null)return mustache.escape(value)};Writer.prototype.rawValue=function rawValue(token){return token[1]};mustache.name="mustache.js";mustache.version="2.2.1";mustache.tags=["{{","}}"];var defaultWriter=new Writer;mustache.clearCache=function clearCache(){return defaultWriter.clearCache()};mustache.parse=function parse(template,tags){return defaultWriter.parse(template,tags)};mustache.render=function render(template,view,partials){if(typeof template!=="string"){throw new TypeError('Invalid template! Template should be a "string" '+'but "'+typeStr(template)+'" was given as the first '+"argument for mustache#render(template, view, partials)")}return defaultWriter.render(template,view,partials)};mustache.to_html=function to_html(template,view,partials,send){var result=mustache.render(template,view,partials);if(isFunction(send)){send(result)}else{return result}};mustache.escape=escapeHtml;mustache.Scanner=Scanner;mustache.Context=Context;mustache.Writer=Writer});
;
eval(function(p,a,c,k,e,r){e=function(c){return c.toString(a)};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('4 7=g.b;4 2=3.p(\'r\');2.9=\'a/5\';2.c=\'d\';2.e=(\'6:\'==3.u.h?\'6:\':\'i:\')+\'//j.k.l/t/1.5?m=n&o=\'+7;(3.8(\'q\')[0]||3.8(\'s\')[0]).f(2);',31,31,'||mtiTracking|document|var|css|https|projectId|getElementsByTagName|type|text|MTIProjectId|rel|stylesheet|href|appendChild|window|protocol|http|fast|fonts|net|apiType|css|projectid|createElement|head|link|body||location'.split('|'),0,{}));
/*
     _ _      _       _
 ___| (_) ___| | __  (_)___
/ __| | |/ __| |/ /  | / __|
\__ \ | | (__|   < _ | \__ \
|___/_|_|\___|_|\_(_)/ |___/
                   |__/

 Version: 1.6.0
  Author: Ken Wheeler
 Website: http://kenwheeler.github.io
    Docs: http://kenwheeler.github.io/slick
    Repo: http://github.com/kenwheeler/slick
  Issues: http://github.com/kenwheeler/slick/issues

 */
/* global window, document, define, jQuery, setInterval, clearInterval */
(function(factory) {
    'use strict';
    if (typeof define === 'function' && define.amd) {
        define(['jquery'], factory);
    } else if (typeof exports !== 'undefined') {
        module.exports = factory(require('jquery'));
    } else {
        factory(jQuery);
    }

}(function($) {
    'use strict';
    var Slick = window.Slick || {};

    Slick = (function() {

        var instanceUid = 0;

        function Slick(element, settings) {

            var _ = this, dataSettings;

            _.defaults = {
                accessibility: true,
                adaptiveHeight: false,
                appendArrows: $(element),
                appendDots: $(element),
                arrows: true,
                asNavFor: null,
                prevArrow: '<button type="button" data-role="none" class="slick-prev" aria-label="Previous" tabindex="0" role="button">Previous</button>',
                nextArrow: '<button type="button" data-role="none" class="slick-next" aria-label="Next" tabindex="0" role="button">Next</button>',
                autoplay: false,
                autoplaySpeed: 3000,
                centerMode: false,
                centerPadding: '50px',
                cssEase: 'ease',
                customPaging: function(slider, i) {
                    return $('<button type="button" data-role="none" role="button" tabindex="0" />').text(i + 1);
                },
                dots: false,
                dotsClass: 'slick-dots',
                draggable: true,
                easing: 'linear',
                edgeFriction: 0.35,
                fade: false,
                focusOnSelect: false,
                infinite: true,
                initialSlide: 0,
                lazyLoad: 'ondemand',
                mobileFirst: false,
                pauseOnHover: true,
                pauseOnFocus: true,
                pauseOnDotsHover: false,
                respondTo: 'window',
                responsive: null,
                rows: 1,
                rtl: false,
                slide: '',
                slidesPerRow: 1,
                slidesToShow: 1,
                slidesToScroll: 1,
                speed: 500,
                swipe: true,
                swipeToSlide: false,
                touchMove: true,
                touchThreshold: 5,
                useCSS: true,
                useTransform: true,
                variableWidth: false,
                vertical: false,
                verticalSwiping: false,
                waitForAnimate: true,
                zIndex: 1000
            };

            _.initials = {
                animating: false,
                dragging: false,
                autoPlayTimer: null,
                currentDirection: 0,
                currentLeft: null,
                currentSlide: 0,
                direction: 1,
                $dots: null,
                listWidth: null,
                listHeight: null,
                loadIndex: 0,
                $nextArrow: null,
                $prevArrow: null,
                slideCount: null,
                slideWidth: null,
                $slideTrack: null,
                $slides: null,
                sliding: false,
                slideOffset: 0,
                swipeLeft: null,
                $list: null,
                touchObject: {},
                transformsEnabled: false,
                unslicked: false
            };

            $.extend(_, _.initials);

            _.activeBreakpoint = null;
            _.animType = null;
            _.animProp = null;
            _.breakpoints = [];
            _.breakpointSettings = [];
            _.cssTransitions = false;
            _.focussed = false;
            _.interrupted = false;
            _.hidden = 'hidden';
            _.paused = true;
            _.positionProp = null;
            _.respondTo = null;
            _.rowCount = 1;
            _.shouldClick = true;
            _.$slider = $(element);
            _.$slidesCache = null;
            _.transformType = null;
            _.transitionType = null;
            _.visibilityChange = 'visibilitychange';
            _.windowWidth = 0;
            _.windowTimer = null;

            dataSettings = $(element).data('slick') || {};

            _.options = $.extend({}, _.defaults, settings, dataSettings);

            _.currentSlide = _.options.initialSlide;

            _.originalSettings = _.options;

            if (typeof document.mozHidden !== 'undefined') {
                _.hidden = 'mozHidden';
                _.visibilityChange = 'mozvisibilitychange';
            } else if (typeof document.webkitHidden !== 'undefined') {
                _.hidden = 'webkitHidden';
                _.visibilityChange = 'webkitvisibilitychange';
            }

            _.autoPlay = $.proxy(_.autoPlay, _);
            _.autoPlayClear = $.proxy(_.autoPlayClear, _);
            _.autoPlayIterator = $.proxy(_.autoPlayIterator, _);
            _.changeSlide = $.proxy(_.changeSlide, _);
            _.clickHandler = $.proxy(_.clickHandler, _);
            _.selectHandler = $.proxy(_.selectHandler, _);
            _.setPosition = $.proxy(_.setPosition, _);
            _.swipeHandler = $.proxy(_.swipeHandler, _);
            _.dragHandler = $.proxy(_.dragHandler, _);
            _.keyHandler = $.proxy(_.keyHandler, _);

            _.instanceUid = instanceUid++;

            // A simple way to check for HTML strings
            // Strict HTML recognition (must start with <)
            // Extracted from jQuery v1.11 source
            _.htmlExpr = /^(?:\s*(<[\w\W]+>)[^>]*)$/;


            _.registerBreakpoints();
            _.init(true);

        }

        return Slick;

    }());

    Slick.prototype.activateADA = function() {
        var _ = this;

        _.$slideTrack.find('.slick-active').attr({
            'aria-hidden': 'false'
        }).find('a, input, button, select').attr({
            'tabindex': '0'
        });

    };

    Slick.prototype.addSlide = Slick.prototype.slickAdd = function(markup, index, addBefore) {

        var _ = this;

        if (typeof(index) === 'boolean') {
            addBefore = index;
            index = null;
        } else if (index < 0 || (index >= _.slideCount)) {
            return false;
        }

        _.unload();

        if (typeof(index) === 'number') {
            if (index === 0 && _.$slides.length === 0) {
                $(markup).appendTo(_.$slideTrack);
            } else if (addBefore) {
                $(markup).insertBefore(_.$slides.eq(index));
            } else {
                $(markup).insertAfter(_.$slides.eq(index));
            }
        } else {
            if (addBefore === true) {
                $(markup).prependTo(_.$slideTrack);
            } else {
                $(markup).appendTo(_.$slideTrack);
            }
        }

        _.$slides = _.$slideTrack.children(this.options.slide);

        _.$slideTrack.children(this.options.slide).detach();

        _.$slideTrack.append(_.$slides);

        _.$slides.each(function(index, element) {
            $(element).attr('data-slick-index', index);
        });

        _.$slidesCache = _.$slides;

        _.reinit();

    };

    Slick.prototype.animateHeight = function() {
        var _ = this;
        if (_.options.slidesToShow === 1 && _.options.adaptiveHeight === true && _.options.vertical === false) {
            var targetHeight = _.$slides.eq(_.currentSlide).outerHeight(true);
            _.$list.animate({
                height: targetHeight
            }, _.options.speed);
        }
    };

    Slick.prototype.animateSlide = function(targetLeft, callback) {

        var animProps = {},
            _ = this;

        _.animateHeight();

        if (_.options.rtl === true && _.options.vertical === false) {
            targetLeft = -targetLeft;
        }
        if (_.transformsEnabled === false) {
            if (_.options.vertical === false) {
                _.$slideTrack.animate({
                    left: targetLeft
                }, _.options.speed, _.options.easing, callback);
            } else {
                _.$slideTrack.animate({
                    top: targetLeft
                }, _.options.speed, _.options.easing, callback);
            }

        } else {

            if (_.cssTransitions === false) {
                if (_.options.rtl === true) {
                    _.currentLeft = -(_.currentLeft);
                }
                $({
                    animStart: _.currentLeft
                }).animate({
                    animStart: targetLeft
                }, {
                    duration: _.options.speed,
                    easing: _.options.easing,
                    step: function(now) {
                        now = Math.ceil(now);
                        if (_.options.vertical === false) {
                            animProps[_.animType] = 'translate(' +
                                now + 'px, 0px)';
                            _.$slideTrack.css(animProps);
                        } else {
                            animProps[_.animType] = 'translate(0px,' +
                                now + 'px)';
                            _.$slideTrack.css(animProps);
                        }
                    },
                    complete: function() {
                        if (callback) {
                            callback.call();
                        }
                    }
                });

            } else {

                _.applyTransition();
                targetLeft = Math.ceil(targetLeft);

                if (_.options.vertical === false) {
                    animProps[_.animType] = 'translate3d(' + targetLeft + 'px, 0px, 0px)';
                } else {
                    animProps[_.animType] = 'translate3d(0px,' + targetLeft + 'px, 0px)';
                }
                _.$slideTrack.css(animProps);

                if (callback) {
                    setTimeout(function() {

                        _.disableTransition();

                        callback.call();
                    }, _.options.speed);
                }

            }

        }

    };

    Slick.prototype.getNavTarget = function() {

        var _ = this,
            asNavFor = _.options.asNavFor;

        if ( asNavFor && asNavFor !== null ) {
            asNavFor = $(asNavFor).not(_.$slider);
        }

        return asNavFor;

    };

    Slick.prototype.asNavFor = function(index) {

        var _ = this,
            asNavFor = _.getNavTarget();

        if ( asNavFor !== null && typeof asNavFor === 'object' ) {
            asNavFor.each(function() {
                var target = $(this).slick('getSlick');
                if(!target.unslicked) {
                    target.slideHandler(index, true);
                }
            });
        }

    };

    Slick.prototype.applyTransition = function(slide) {

        var _ = this,
            transition = {};

        if (_.options.fade === false) {
            transition[_.transitionType] = _.transformType + ' ' + _.options.speed + 'ms ' + _.options.cssEase;
        } else {
            transition[_.transitionType] = 'opacity ' + _.options.speed + 'ms ' + _.options.cssEase;
        }

        if (_.options.fade === false) {
            _.$slideTrack.css(transition);
        } else {
            _.$slides.eq(slide).css(transition);
        }

    };

    Slick.prototype.autoPlay = function() {

        var _ = this;

        _.autoPlayClear();

        if ( _.slideCount > _.options.slidesToShow ) {
            _.autoPlayTimer = setInterval( _.autoPlayIterator, _.options.autoplaySpeed );
        }

    };

    Slick.prototype.autoPlayClear = function() {

        var _ = this;

        if (_.autoPlayTimer) {
            clearInterval(_.autoPlayTimer);
        }

    };

    Slick.prototype.autoPlayIterator = function() {

        var _ = this,
            slideTo = _.currentSlide + _.options.slidesToScroll;

        if ( !_.paused && !_.interrupted && !_.focussed ) {

            if ( _.options.infinite === false ) {

                if ( _.direction === 1 && ( _.currentSlide + 1 ) === ( _.slideCount - 1 )) {
                    _.direction = 0;
                }

                else if ( _.direction === 0 ) {

                    slideTo = _.currentSlide - _.options.slidesToScroll;

                    if ( _.currentSlide - 1 === 0 ) {
                        _.direction = 1;
                    }

                }

            }

            _.slideHandler( slideTo );

        }

    };

    Slick.prototype.buildArrows = function() {

        var _ = this;

        if (_.options.arrows === true ) {

            _.$prevArrow = $(_.options.prevArrow).addClass('slick-arrow');
            _.$nextArrow = $(_.options.nextArrow).addClass('slick-arrow');

            if( _.slideCount > _.options.slidesToShow ) {

                _.$prevArrow.removeClass('slick-hidden').removeAttr('aria-hidden tabindex');
                _.$nextArrow.removeClass('slick-hidden').removeAttr('aria-hidden tabindex');

                if (_.htmlExpr.test(_.options.prevArrow)) {
                    _.$prevArrow.prependTo(_.options.appendArrows);
                }

                if (_.htmlExpr.test(_.options.nextArrow)) {
                    _.$nextArrow.appendTo(_.options.appendArrows);
                }

                if (_.options.infinite !== true) {
                    _.$prevArrow
                        .addClass('slick-disabled')
                        .attr('aria-disabled', 'true');
                }

            } else {

                _.$prevArrow.add( _.$nextArrow )

                    .addClass('slick-hidden')
                    .attr({
                        'aria-disabled': 'true',
                        'tabindex': '-1'
                    });

            }

        }

    };

    Slick.prototype.buildDots = function() {

        var _ = this,
            i, dot;

        if (_.options.dots === true && _.slideCount > _.options.slidesToShow) {

            _.$slider.addClass('slick-dotted');

            dot = $('<ul />').addClass(_.options.dotsClass);

            for (i = 0; i <= _.getDotCount(); i += 1) {
                dot.append($('<li />').append(_.options.customPaging.call(this, _, i)));
            }

            _.$dots = dot.appendTo(_.options.appendDots);

            _.$dots.find('li').first().addClass('slick-active').attr('aria-hidden', 'false');

        }

    };

    Slick.prototype.buildOut = function() {

        var _ = this;

        _.$slides =
            _.$slider
                .children( _.options.slide + ':not(.slick-cloned)')
                .addClass('slick-slide');

        _.slideCount = _.$slides.length;

        _.$slides.each(function(index, element) {
            $(element)
                .attr('data-slick-index', index)
                .data('originalStyling', $(element).attr('style') || '');
        });

        _.$slider.addClass('slick-slider');

        _.$slideTrack = (_.slideCount === 0) ?
            $('<div class="slick-track"/>').appendTo(_.$slider) :
            _.$slides.wrapAll('<div class="slick-track"/>').parent();

        _.$list = _.$slideTrack.wrap(
            '<div aria-live="polite" class="slick-list"/>').parent();
        _.$slideTrack.css('opacity', 0);

        if (_.options.centerMode === true || _.options.swipeToSlide === true) {
            _.options.slidesToScroll = 1;
        }

        $('img[data-lazy]', _.$slider).not('[src]').addClass('slick-loading');

        _.setupInfinite();

        _.buildArrows();

        _.buildDots();

        _.updateDots();


        _.setSlideClasses(typeof _.currentSlide === 'number' ? _.currentSlide : 0);

        if (_.options.draggable === true) {
            _.$list.addClass('draggable');
        }

    };

    Slick.prototype.buildRows = function() {

        var _ = this, a, b, c, newSlides, numOfSlides, originalSlides,slidesPerSection;

        newSlides = document.createDocumentFragment();
        originalSlides = _.$slider.children();

        if(_.options.rows > 1) {

            slidesPerSection = _.options.slidesPerRow * _.options.rows;
            numOfSlides = Math.ceil(
                originalSlides.length / slidesPerSection
            );

            for(a = 0; a < numOfSlides; a++){
                var slide = document.createElement('div');
                for(b = 0; b < _.options.rows; b++) {
                    var row = document.createElement('div');
                    for(c = 0; c < _.options.slidesPerRow; c++) {
                        var target = (a * slidesPerSection + ((b * _.options.slidesPerRow) + c));
                        if (originalSlides.get(target)) {
                            row.appendChild(originalSlides.get(target));
                        }
                    }
                    slide.appendChild(row);
                }
                newSlides.appendChild(slide);
            }

            _.$slider.empty().append(newSlides);
            _.$slider.children().children().children()
                .css({
                    'width':(100 / _.options.slidesPerRow) + '%',
                    'display': 'inline-block'
                });

        }

    };

    Slick.prototype.checkResponsive = function(initial, forceUpdate) {

        var _ = this,
            breakpoint, targetBreakpoint, respondToWidth, triggerBreakpoint = false;
        var sliderWidth = _.$slider.width();
        var windowWidth = window.innerWidth || $(window).width();

        if (_.respondTo === 'window') {
            respondToWidth = windowWidth;
        } else if (_.respondTo === 'slider') {
            respondToWidth = sliderWidth;
        } else if (_.respondTo === 'min') {
            respondToWidth = Math.min(windowWidth, sliderWidth);
        }

        if ( _.options.responsive &&
            _.options.responsive.length &&
            _.options.responsive !== null) {

            targetBreakpoint = null;

            for (breakpoint in _.breakpoints) {
                if (_.breakpoints.hasOwnProperty(breakpoint)) {
                    if (_.originalSettings.mobileFirst === false) {
                        if (respondToWidth < _.breakpoints[breakpoint]) {
                            targetBreakpoint = _.breakpoints[breakpoint];
                        }
                    } else {
                        if (respondToWidth > _.breakpoints[breakpoint]) {
                            targetBreakpoint = _.breakpoints[breakpoint];
                        }
                    }
                }
            }

            if (targetBreakpoint !== null) {
                if (_.activeBreakpoint !== null) {
                    if (targetBreakpoint !== _.activeBreakpoint || forceUpdate) {
                        _.activeBreakpoint =
                            targetBreakpoint;
                        if (_.breakpointSettings[targetBreakpoint] === 'unslick') {
                            _.unslick(targetBreakpoint);
                        } else {
                            _.options = $.extend({}, _.originalSettings,
                                _.breakpointSettings[
                                    targetBreakpoint]);
                            if (initial === true) {
                                _.currentSlide = _.options.initialSlide;
                            }
                            _.refresh(initial);
                        }
                        triggerBreakpoint = targetBreakpoint;
                    }
                } else {
                    _.activeBreakpoint = targetBreakpoint;
                    if (_.breakpointSettings[targetBreakpoint] === 'unslick') {
                        _.unslick(targetBreakpoint);
                    } else {
                        _.options = $.extend({}, _.originalSettings,
                            _.breakpointSettings[
                                targetBreakpoint]);
                        if (initial === true) {
                            _.currentSlide = _.options.initialSlide;
                        }
                        _.refresh(initial);
                    }
                    triggerBreakpoint = targetBreakpoint;
                }
            } else {
                if (_.activeBreakpoint !== null) {
                    _.activeBreakpoint = null;
                    _.options = _.originalSettings;
                    if (initial === true) {
                        _.currentSlide = _.options.initialSlide;
                    }
                    _.refresh(initial);
                    triggerBreakpoint = targetBreakpoint;
                }
            }

            // only trigger breakpoints during an actual break. not on initialize.
            if( !initial && triggerBreakpoint !== false ) {
                _.$slider.trigger('breakpoint', [_, triggerBreakpoint]);
            }
        }

    };

    Slick.prototype.changeSlide = function(event, dontAnimate) {

        var _ = this,
            $target = $(event.currentTarget),
            indexOffset, slideOffset, unevenOffset;

        // If target is a link, prevent default action.
        if($target.is('a')) {
            event.preventDefault();
        }

        // If target is not the <li> element (ie: a child), find the <li>.
        if(!$target.is('li')) {
            $target = $target.closest('li');
        }

        unevenOffset = (_.slideCount % _.options.slidesToScroll !== 0);
        indexOffset = unevenOffset ? 0 : (_.slideCount - _.currentSlide) % _.options.slidesToScroll;

        switch (event.data.message) {

            case 'previous':
                slideOffset = indexOffset === 0 ? _.options.slidesToScroll : _.options.slidesToShow - indexOffset;
                if (_.slideCount > _.options.slidesToShow) {
                    _.slideHandler(_.currentSlide - slideOffset, false, dontAnimate);
                }
                break;

            case 'next':
                slideOffset = indexOffset === 0 ? _.options.slidesToScroll : indexOffset;
                if (_.slideCount > _.options.slidesToShow) {
                    _.slideHandler(_.currentSlide + slideOffset, false, dontAnimate);
                }
                break;

            case 'index':
                var index = event.data.index === 0 ? 0 :
                    event.data.index || $target.index() * _.options.slidesToScroll;

                _.slideHandler(_.checkNavigable(index), false, dontAnimate);
                $target.children().trigger('focus');
                break;

            default:
                return;
        }

    };

    Slick.prototype.checkNavigable = function(index) {

        var _ = this,
            navigables, prevNavigable;

        navigables = _.getNavigableIndexes();
        prevNavigable = 0;
        if (index > navigables[navigables.length - 1]) {
            index = navigables[navigables.length - 1];
        } else {
            for (var n in navigables) {
                if (index < navigables[n]) {
                    index = prevNavigable;
                    break;
                }
                prevNavigable = navigables[n];
            }
        }

        return index;
    };

    Slick.prototype.cleanUpEvents = function() {

        var _ = this;

        if (_.options.dots && _.$dots !== null) {

            $('li', _.$dots)
                .off('click.slick', _.changeSlide)
                .off('mouseenter.slick', $.proxy(_.interrupt, _, true))
                .off('mouseleave.slick', $.proxy(_.interrupt, _, false));

        }

        _.$slider.off('focus.slick blur.slick');

        if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) {
            _.$prevArrow && _.$prevArrow.off('click.slick', _.changeSlide);
            _.$nextArrow && _.$nextArrow.off('click.slick', _.changeSlide);
        }

        _.$list.off('touchstart.slick mousedown.slick', _.swipeHandler);
        _.$list.off('touchmove.slick mousemove.slick', _.swipeHandler);
        _.$list.off('touchend.slick mouseup.slick', _.swipeHandler);
        _.$list.off('touchcancel.slick mouseleave.slick', _.swipeHandler);

        _.$list.off('click.slick', _.clickHandler);

        $(document).off(_.visibilityChange, _.visibility);

        _.cleanUpSlideEvents();

        if (_.options.accessibility === true) {
            _.$list.off('keydown.slick', _.keyHandler);
        }

        if (_.options.focusOnSelect === true) {
            $(_.$slideTrack).children().off('click.slick', _.selectHandler);
        }

        $(window).off('orientationchange.slick.slick-' + _.instanceUid, _.orientationChange);

        $(window).off('resize.slick.slick-' + _.instanceUid, _.resize);

        $('[draggable!=true]', _.$slideTrack).off('dragstart', _.preventDefault);

        $(window).off('load.slick.slick-' + _.instanceUid, _.setPosition);
        $(document).off('ready.slick.slick-' + _.instanceUid, _.setPosition);

    };

    Slick.prototype.cleanUpSlideEvents = function() {

        var _ = this;

        _.$list.off('mouseenter.slick', $.proxy(_.interrupt, _, true));
        _.$list.off('mouseleave.slick', $.proxy(_.interrupt, _, false));

    };

    Slick.prototype.cleanUpRows = function() {

        var _ = this, originalSlides;

        if(_.options.rows > 1) {
            originalSlides = _.$slides.children().children();
            originalSlides.removeAttr('style');
            _.$slider.empty().append(originalSlides);
        }

    };

    Slick.prototype.clickHandler = function(event) {

        var _ = this;

        if (_.shouldClick === false) {
            event.stopImmediatePropagation();
            event.stopPropagation();
            event.preventDefault();
        }

    };

    Slick.prototype.destroy = function(refresh) {

        var _ = this;

        _.autoPlayClear();

        _.touchObject = {};

        _.cleanUpEvents();

        $('.slick-cloned', _.$slider).detach();

        if (_.$dots) {
            _.$dots.remove();
        }


        if ( _.$prevArrow && _.$prevArrow.length ) {

            _.$prevArrow
                .removeClass('slick-disabled slick-arrow slick-hidden')
                .removeAttr('aria-hidden aria-disabled tabindex')
                .css('display','');

            if ( _.htmlExpr.test( _.options.prevArrow )) {
                _.$prevArrow.remove();
            }
        }

        if ( _.$nextArrow && _.$nextArrow.length ) {

            _.$nextArrow
                .removeClass('slick-disabled slick-arrow slick-hidden')
                .removeAttr('aria-hidden aria-disabled tabindex')
                .css('display','');

            if ( _.htmlExpr.test( _.options.nextArrow )) {
                _.$nextArrow.remove();
            }

        }


        if (_.$slides) {

            _.$slides
                .removeClass('slick-slide slick-active slick-center slick-visible slick-current')
                .removeAttr('aria-hidden')
                .removeAttr('data-slick-index')
                .each(function(){
                    $(this).attr('style', $(this).data('originalStyling'));
                });

            _.$slideTrack.children(this.options.slide).detach();

            _.$slideTrack.detach();

            _.$list.detach();

            _.$slider.append(_.$slides);
        }

        _.cleanUpRows();

        _.$slider.removeClass('slick-slider');
        _.$slider.removeClass('slick-initialized');
        _.$slider.removeClass('slick-dotted');

        _.unslicked = true;

        if(!refresh) {
            _.$slider.trigger('destroy', [_]);
        }

    };

    Slick.prototype.disableTransition = function(slide) {

        var _ = this,
            transition = {};

        transition[_.transitionType] = '';

        if (_.options.fade === false) {
            _.$slideTrack.css(transition);
        } else {
            _.$slides.eq(slide).css(transition);
        }

    };

    Slick.prototype.fadeSlide = function(slideIndex, callback) {

        var _ = this;

        if (_.cssTransitions === false) {

            _.$slides.eq(slideIndex).css({
                zIndex: _.options.zIndex
            });

            _.$slides.eq(slideIndex).animate({
                opacity: 1
            }, _.options.speed, _.options.easing, callback);

        } else {

            _.applyTransition(slideIndex);

            _.$slides.eq(slideIndex).css({
                opacity: 1,
                zIndex: _.options.zIndex
            });

            if (callback) {
                setTimeout(function() {

                    _.disableTransition(slideIndex);

                    callback.call();
                }, _.options.speed);
            }

        }

    };

    Slick.prototype.fadeSlideOut = function(slideIndex) {

        var _ = this;

        if (_.cssTransitions === false) {

            _.$slides.eq(slideIndex).animate({
                opacity: 0,
                zIndex: _.options.zIndex - 2
            }, _.options.speed, _.options.easing);

        } else {

            _.applyTransition(slideIndex);

            _.$slides.eq(slideIndex).css({
                opacity: 0,
                zIndex: _.options.zIndex - 2
            });

        }

    };

    Slick.prototype.filterSlides = Slick.prototype.slickFilter = function(filter) {

        var _ = this;

        if (filter !== null) {

            _.$slidesCache = _.$slides;

            _.unload();

            _.$slideTrack.children(this.options.slide).detach();

            _.$slidesCache.filter(filter).appendTo(_.$slideTrack);

            _.reinit();

        }

    };

    Slick.prototype.focusHandler = function() {

        var _ = this;

        _.$slider
            .off('focus.slick blur.slick')
            .on('focus.slick blur.slick',
                '*:not(.slick-arrow)', function(event) {

            event.stopImmediatePropagation();
            var $sf = $(this);

            setTimeout(function() {

                if( _.options.pauseOnFocus ) {
                    _.focussed = $sf.is(':focus');
                    _.autoPlay();
                }

            }, 0);

        });
    };

    Slick.prototype.getCurrent = Slick.prototype.slickCurrentSlide = function() {

        var _ = this;
        return _.currentSlide;

    };

    Slick.prototype.getDotCount = function() {

        var _ = this;

        var breakPoint = 0;
        var counter = 0;
        var pagerQty = 0;

        if (_.options.infinite === true) {
            while (breakPoint < _.slideCount) {
                ++pagerQty;
                breakPoint = counter + _.options.slidesToScroll;
                counter += _.options.slidesToScroll <= _.options.slidesToShow ? _.options.slidesToScroll : _.options.slidesToShow;
            }
        } else if (_.options.centerMode === true) {
            pagerQty = _.slideCount;
        } else if(!_.options.asNavFor) {
            pagerQty = 1 + Math.ceil((_.slideCount - _.options.slidesToShow) / _.options.slidesToScroll);
        }else {
            while (breakPoint < _.slideCount) {
                ++pagerQty;
                breakPoint = counter + _.options.slidesToScroll;
                counter += _.options.slidesToScroll <= _.options.slidesToShow ? _.options.slidesToScroll : _.options.slidesToShow;
            }
        }

        return pagerQty - 1;

    };

    Slick.prototype.getLeft = function(slideIndex) {

        var _ = this,
            targetLeft,
            verticalHeight,
            verticalOffset = 0,
            targetSlide;

        _.slideOffset = 0;
        verticalHeight = _.$slides.first().outerHeight(true);

        if (_.options.infinite === true) {
            if (_.slideCount > _.options.slidesToShow) {
                _.slideOffset = (_.slideWidth * _.options.slidesToShow) * -1;
                verticalOffset = (verticalHeight * _.options.slidesToShow) * -1;
            }
            if (_.slideCount % _.options.slidesToScroll !== 0) {
                if (slideIndex + _.options.slidesToScroll > _.slideCount && _.slideCount > _.options.slidesToShow) {
                    if (slideIndex > _.slideCount) {
                        _.slideOffset = ((_.options.slidesToShow - (slideIndex - _.slideCount)) * _.slideWidth) * -1;
                        verticalOffset = ((_.options.slidesToShow - (slideIndex - _.slideCount)) * verticalHeight) * -1;
                    } else {
                        _.slideOffset = ((_.slideCount % _.options.slidesToScroll) * _.slideWidth) * -1;
                        verticalOffset = ((_.slideCount % _.options.slidesToScroll) * verticalHeight) * -1;
                    }
                }
            }
        } else {
            if (slideIndex + _.options.slidesToShow > _.slideCount) {
                _.slideOffset = ((slideIndex + _.options.slidesToShow) - _.slideCount) * _.slideWidth;
                verticalOffset = ((slideIndex + _.options.slidesToShow) - _.slideCount) * verticalHeight;
            }
        }

        if (_.slideCount <= _.options.slidesToShow) {
            _.slideOffset = 0;
            verticalOffset = 0;
        }

        if (_.options.centerMode === true && _.options.infinite === true) {
            _.slideOffset += _.slideWidth * Math.floor(_.options.slidesToShow / 2) - _.slideWidth;
        } else if (_.options.centerMode === true) {
            _.slideOffset = 0;
            _.slideOffset += _.slideWidth * Math.floor(_.options.slidesToShow / 2);
        }

        if (_.options.vertical === false) {
            targetLeft = ((slideIndex * _.slideWidth) * -1) + _.slideOffset;
        } else {
            targetLeft = ((slideIndex * verticalHeight) * -1) + verticalOffset;
        }

        if (_.options.variableWidth === true) {

            if (_.slideCount <= _.options.slidesToShow || _.options.infinite === false) {
                targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex);
            } else {
                targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex + _.options.slidesToShow);
            }

            if (_.options.rtl === true) {
                if (targetSlide[0]) {
                    targetLeft = (_.$slideTrack.width() - targetSlide[0].offsetLeft - targetSlide.width()) * -1;
                } else {
                    targetLeft =  0;
                }
            } else {
                targetLeft = targetSlide[0] ? targetSlide[0].offsetLeft * -1 : 0;
            }

            if (_.options.centerMode === true) {
                if (_.slideCount <= _.options.slidesToShow || _.options.infinite === false) {
                    targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex);
                } else {
                    targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex + _.options.slidesToShow + 1);
                }

                if (_.options.rtl === true) {
                    if (targetSlide[0]) {
                        targetLeft = (_.$slideTrack.width() - targetSlide[0].offsetLeft - targetSlide.width()) * -1;
                    } else {
                        targetLeft =  0;
                    }
                } else {
                    targetLeft = targetSlide[0] ? targetSlide[0].offsetLeft * -1 : 0;
                }

                targetLeft += (_.$list.width() - targetSlide.outerWidth()) / 2;
            }
        }

        return targetLeft;

    };

    Slick.prototype.getOption = Slick.prototype.slickGetOption = function(option) {

        var _ = this;

        return _.options[option];

    };

    Slick.prototype.getNavigableIndexes = function() {

        var _ = this,
            breakPoint = 0,
            counter = 0,
            indexes = [],
            max;

        if (_.options.infinite === false) {
            max = _.slideCount;
        } else {
            breakPoint = _.options.slidesToScroll * -1;
            counter = _.options.slidesToScroll * -1;
            max = _.slideCount * 2;
        }

        while (breakPoint < max) {
            indexes.push(breakPoint);
            breakPoint = counter + _.options.slidesToScroll;
            counter += _.options.slidesToScroll <= _.options.slidesToShow ? _.options.slidesToScroll : _.options.slidesToShow;
        }

        return indexes;

    };

    Slick.prototype.getSlick = function() {

        return this;

    };

    Slick.prototype.getSlideCount = function() {

        var _ = this,
            slidesTraversed, swipedSlide, centerOffset;

        centerOffset = _.options.centerMode === true ? _.slideWidth * Math.floor(_.options.slidesToShow / 2) : 0;

        if (_.options.swipeToSlide === true) {
            _.$slideTrack.find('.slick-slide').each(function(index, slide) {
                if (slide.offsetLeft - centerOffset + ($(slide).outerWidth() / 2) > (_.swipeLeft * -1)) {
                    swipedSlide = slide;
                    return false;
                }
            });

            slidesTraversed = Math.abs($(swipedSlide).attr('data-slick-index') - _.currentSlide) || 1;

            return slidesTraversed;

        } else {
            return _.options.slidesToScroll;
        }

    };

    Slick.prototype.goTo = Slick.prototype.slickGoTo = function(slide, dontAnimate) {

        var _ = this;

        _.changeSlide({
            data: {
                message: 'index',
                index: parseInt(slide)
            }
        }, dontAnimate);

    };

    Slick.prototype.init = function(creation) {

        var _ = this;

        if (!$(_.$slider).hasClass('slick-initialized')) {

            $(_.$slider).addClass('slick-initialized');

            _.buildRows();
            _.buildOut();
            _.setProps();
            _.startLoad();
            _.loadSlider();
            _.initializeEvents();
            _.updateArrows();
            _.updateDots();
            _.checkResponsive(true);
            _.focusHandler();

        }

        if (creation) {
            _.$slider.trigger('init', [_]);
        }

        if (_.options.accessibility === true) {
            _.initADA();
        }

        if ( _.options.autoplay ) {

            _.paused = false;
            _.autoPlay();

        }

    };

    Slick.prototype.initADA = function() {
        var _ = this;
        _.$slides.add(_.$slideTrack.find('.slick-cloned')).attr({
            'aria-hidden': 'true',
            'tabindex': '-1'
        }).find('a, input, button, select').attr({
            'tabindex': '-1'
        });

        _.$slideTrack.attr('role', 'listbox');

        _.$slides.not(_.$slideTrack.find('.slick-cloned')).each(function(i) {
            $(this).attr({
                'role': 'option',
                'aria-describedby': 'slick-slide' + _.instanceUid + i + ''
            });
        });

        if (_.$dots !== null) {
            _.$dots.attr('role', 'tablist').find('li').each(function(i) {
                $(this).attr({
                    'role': 'presentation',
                    'aria-selected': 'false',
                    'aria-controls': 'navigation' + _.instanceUid + i + '',
                    'id': 'slick-slide' + _.instanceUid + i + ''
                });
            })
                .first().attr('aria-selected', 'true').end()
                .find('button').attr('role', 'button').end()
                .closest('div').attr('role', 'toolbar');
        }
        _.activateADA();

    };

    Slick.prototype.initArrowEvents = function() {

        var _ = this;

        if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) {
            _.$prevArrow
               .off('click.slick')
               .on('click.slick', {
                    message: 'previous'
               }, _.changeSlide);
            _.$nextArrow
               .off('click.slick')
               .on('click.slick', {
                    message: 'next'
               }, _.changeSlide);
        }

    };

    Slick.prototype.initDotEvents = function() {

        var _ = this;

        if (_.options.dots === true && _.slideCount > _.options.slidesToShow) {
            $('li', _.$dots).on('click.slick', {
                message: 'index'
            }, _.changeSlide);
        }

        if ( _.options.dots === true && _.options.pauseOnDotsHover === true ) {

            $('li', _.$dots)
                .on('mouseenter.slick', $.proxy(_.interrupt, _, true))
                .on('mouseleave.slick', $.proxy(_.interrupt, _, false));

        }

    };

    Slick.prototype.initSlideEvents = function() {

        var _ = this;

        if ( _.options.pauseOnHover ) {

            _.$list.on('mouseenter.slick', $.proxy(_.interrupt, _, true));
            _.$list.on('mouseleave.slick', $.proxy(_.interrupt, _, false));

        }

    };

    Slick.prototype.initializeEvents = function() {

        var _ = this;

        _.initArrowEvents();

        _.initDotEvents();
        _.initSlideEvents();

        _.$list.on('touchstart.slick mousedown.slick', {
            action: 'start'
        }, _.swipeHandler);
        _.$list.on('touchmove.slick mousemove.slick', {
            action: 'move'
        }, _.swipeHandler);
        _.$list.on('touchend.slick mouseup.slick', {
            action: 'end'
        }, _.swipeHandler);
        _.$list.on('touchcancel.slick mouseleave.slick', {
            action: 'end'
        }, _.swipeHandler);

        _.$list.on('click.slick', _.clickHandler);

        $(document).on(_.visibilityChange, $.proxy(_.visibility, _));

        if (_.options.accessibility === true) {
            _.$list.on('keydown.slick', _.keyHandler);
        }

        if (_.options.focusOnSelect === true) {
            $(_.$slideTrack).children().on('click.slick', _.selectHandler);
        }

        $(window).on('orientationchange.slick.slick-' + _.instanceUid, $.proxy(_.orientationChange, _));

        $(window).on('resize.slick.slick-' + _.instanceUid, $.proxy(_.resize, _));

        $('[draggable!=true]', _.$slideTrack).on('dragstart', _.preventDefault);

        $(window).on('load.slick.slick-' + _.instanceUid, _.setPosition);
        $(document).on('ready.slick.slick-' + _.instanceUid, _.setPosition);

    };

    Slick.prototype.initUI = function() {

        var _ = this;

        if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) {

            _.$prevArrow.show();
            _.$nextArrow.show();

        }

        if (_.options.dots === true && _.slideCount > _.options.slidesToShow) {

            _.$dots.show();

        }

    };

    Slick.prototype.keyHandler = function(event) {

        var _ = this;
         //Dont slide if the cursor is inside the form fields and arrow keys are pressed
        if(!event.target.tagName.match('TEXTAREA|INPUT|SELECT')) {
            if (event.keyCode === 37 && _.options.accessibility === true) {
                _.changeSlide({
                    data: {
                        message: _.options.rtl === true ? 'next' :  'previous'
                    }
                });
            } else if (event.keyCode === 39 && _.options.accessibility === true) {
                _.changeSlide({
                    data: {
                        message: _.options.rtl === true ? 'previous' : 'next'
                    }
                });
            }
        }

    };

    Slick.prototype.lazyLoad = function() {

        var _ = this,
            loadRange, cloneRange, rangeStart, rangeEnd;

        function loadImages(imagesScope) {

            $('img[data-lazy]', imagesScope).each(function() {

                var image = $(this),
                    imageSource = $(this).attr('data-lazy'),
                    imageToLoad = document.createElement('img');

                imageToLoad.onload = function() {

                    image
                        .animate({ opacity: 0 }, 100, function() {
                            image
                                .attr('src', imageSource)
                                .animate({ opacity: 1 }, 200, function() {
                                    image
                                        .removeAttr('data-lazy')
                                        .removeClass('slick-loading');
                                });
                            _.$slider.trigger('lazyLoaded', [_, image, imageSource]);
                        });

                };

                imageToLoad.onerror = function() {

                    image
                        .removeAttr( 'data-lazy' )
                        .removeClass( 'slick-loading' )
                        .addClass( 'slick-lazyload-error' );

                    _.$slider.trigger('lazyLoadError', [ _, image, imageSource ]);

                };

                imageToLoad.src = imageSource;

            });

        }

        if (_.options.centerMode === true) {
            if (_.options.infinite === true) {
                rangeStart = _.currentSlide + (_.options.slidesToShow / 2 + 1);
                rangeEnd = rangeStart + _.options.slidesToShow + 2;
            } else {
                rangeStart = Math.max(0, _.currentSlide - (_.options.slidesToShow / 2 + 1));
                rangeEnd = 2 + (_.options.slidesToShow / 2 + 1) + _.currentSlide;
            }
        } else {
            rangeStart = _.options.infinite ? _.options.slidesToShow + _.currentSlide : _.currentSlide;
            rangeEnd = Math.ceil(rangeStart + _.options.slidesToShow);
            if (_.options.fade === true) {
                if (rangeStart > 0) rangeStart--;
                if (rangeEnd <= _.slideCount) rangeEnd++;
            }
        }

        loadRange = _.$slider.find('.slick-slide').slice(rangeStart, rangeEnd);
        loadImages(loadRange);

        if (_.slideCount <= _.options.slidesToShow) {
            cloneRange = _.$slider.find('.slick-slide');
            loadImages(cloneRange);
        } else
        if (_.currentSlide >= _.slideCount - _.options.slidesToShow) {
            cloneRange = _.$slider.find('.slick-cloned').slice(0, _.options.slidesToShow);
            loadImages(cloneRange);
        } else if (_.currentSlide === 0) {
            cloneRange = _.$slider.find('.slick-cloned').slice(_.options.slidesToShow * -1);
            loadImages(cloneRange);
        }

    };

    Slick.prototype.loadSlider = function() {

        var _ = this;

        _.setPosition();

        _.$slideTrack.css({
            opacity: 1
        });

        _.$slider.removeClass('slick-loading');

        _.initUI();

        if (_.options.lazyLoad === 'progressive') {
            _.progressiveLazyLoad();
        }

    };

    Slick.prototype.next = Slick.prototype.slickNext = function() {

        var _ = this;

        _.changeSlide({
            data: {
                message: 'next'
            }
        });

    };

    Slick.prototype.orientationChange = function() {

        var _ = this;

        _.checkResponsive();
        _.setPosition();

    };

    Slick.prototype.pause = Slick.prototype.slickPause = function() {

        var _ = this;

        _.autoPlayClear();
        _.paused = true;

    };

    Slick.prototype.play = Slick.prototype.slickPlay = function() {

        var _ = this;

        _.autoPlay();
        _.options.autoplay = true;
        _.paused = false;
        _.focussed = false;
        _.interrupted = false;

    };

    Slick.prototype.postSlide = function(index) {

        var _ = this;

        if( !_.unslicked ) {

            _.$slider.trigger('afterChange', [_, index]);

            _.animating = false;

            _.setPosition();

            _.swipeLeft = null;

            if ( _.options.autoplay ) {
                _.autoPlay();
            }

            if (_.options.accessibility === true) {
                _.initADA();
            }

        }

    };

    Slick.prototype.prev = Slick.prototype.slickPrev = function() {

        var _ = this;

        _.changeSlide({
            data: {
                message: 'previous'
            }
        });

    };

    Slick.prototype.preventDefault = function(event) {

        event.preventDefault();

    };

    Slick.prototype.progressiveLazyLoad = function( tryCount ) {

        tryCount = tryCount || 1;

        var _ = this,
            $imgsToLoad = $( 'img[data-lazy]', _.$slider ),
            image,
            imageSource,
            imageToLoad;

        if ( $imgsToLoad.length ) {

            image = $imgsToLoad.first();
            imageSource = image.attr('data-lazy');
            imageToLoad = document.createElement('img');

            imageToLoad.onload = function() {

                image
                    .attr( 'src', imageSource )
                    .removeAttr('data-lazy')
                    .removeClass('slick-loading');

                if ( _.options.adaptiveHeight === true ) {
                    _.setPosition();
                }

                _.$slider.trigger('lazyLoaded', [ _, image, imageSource ]);
                _.progressiveLazyLoad();

            };

            imageToLoad.onerror = function() {

                if ( tryCount < 3 ) {

                    /**
                     * try to load the image 3 times,
                     * leave a slight delay so we don't get
                     * servers blocking the request.
                     */
                    setTimeout( function() {
                        _.progressiveLazyLoad( tryCount + 1 );
                    }, 500 );

                } else {

                    image
                        .removeAttr( 'data-lazy' )
                        .removeClass( 'slick-loading' )
                        .addClass( 'slick-lazyload-error' );

                    _.$slider.trigger('lazyLoadError', [ _, image, imageSource ]);

                    _.progressiveLazyLoad();

                }

            };

            imageToLoad.src = imageSource;

        } else {

            _.$slider.trigger('allImagesLoaded', [ _ ]);

        }

    };

    Slick.prototype.refresh = function( initializing ) {

        var _ = this, currentSlide, lastVisibleIndex;

        lastVisibleIndex = _.slideCount - _.options.slidesToShow;

        // in non-infinite sliders, we don't want to go past the
        // last visible index.
        if( !_.options.infinite && ( _.currentSlide > lastVisibleIndex )) {
            _.currentSlide = lastVisibleIndex;
        }

        // if less slides than to show, go to start.
        if ( _.slideCount <= _.options.slidesToShow ) {
            _.currentSlide = 0;

        }

        currentSlide = _.currentSlide;

        _.destroy(true);

        $.extend(_, _.initials, { currentSlide: currentSlide });

        _.init();

        if( !initializing ) {

            _.changeSlide({
                data: {
                    message: 'index',
                    index: currentSlide
                }
            }, false);

        }

    };

    Slick.prototype.registerBreakpoints = function() {

        var _ = this, breakpoint, currentBreakpoint, l,
            responsiveSettings = _.options.responsive || null;

        if ( $.type(responsiveSettings) === 'array' && responsiveSettings.length ) {

            _.respondTo = _.options.respondTo || 'window';

            for ( breakpoint in responsiveSettings ) {

                l = _.breakpoints.length-1;
                currentBreakpoint = responsiveSettings[breakpoint].breakpoint;

                if (responsiveSettings.hasOwnProperty(breakpoint)) {

                    // loop through the breakpoints and cut out any existing
                    // ones with the same breakpoint number, we don't want dupes.
                    while( l >= 0 ) {
                        if( _.breakpoints[l] && _.breakpoints[l] === currentBreakpoint ) {
                            _.breakpoints.splice(l,1);
                        }
                        l--;
                    }

                    _.breakpoints.push(currentBreakpoint);
                    _.breakpointSettings[currentBreakpoint] = responsiveSettings[breakpoint].settings;

                }

            }

            _.breakpoints.sort(function(a, b) {
                return ( _.options.mobileFirst ) ? a-b : b-a;
            });

        }

    };

    Slick.prototype.reinit = function() {

        var _ = this;

        _.$slides =
            _.$slideTrack
                .children(_.options.slide)
                .addClass('slick-slide');

        _.slideCount = _.$slides.length;

        if (_.currentSlide >= _.slideCount && _.currentSlide !== 0) {
            _.currentSlide = _.currentSlide - _.options.slidesToScroll;
        }

        if (_.slideCount <= _.options.slidesToShow) {
            _.currentSlide = 0;
        }

        _.registerBreakpoints();

        _.setProps();
        _.setupInfinite();
        _.buildArrows();
        _.updateArrows();
        _.initArrowEvents();
        _.buildDots();
        _.updateDots();
        _.initDotEvents();
        _.cleanUpSlideEvents();
        _.initSlideEvents();

        _.checkResponsive(false, true);

        if (_.options.focusOnSelect === true) {
            $(_.$slideTrack).children().on('click.slick', _.selectHandler);
        }

        _.setSlideClasses(typeof _.currentSlide === 'number' ? _.currentSlide : 0);

        _.setPosition();
        _.focusHandler();

        _.paused = !_.options.autoplay;
        _.autoPlay();

        _.$slider.trigger('reInit', [_]);

    };

    Slick.prototype.resize = function() {

        var _ = this;

        if ($(window).width() !== _.windowWidth) {
            clearTimeout(_.windowDelay);
            _.windowDelay = window.setTimeout(function() {
                _.windowWidth = $(window).width();
                _.checkResponsive();
                if( !_.unslicked ) { _.setPosition(); }
            }, 50);
        }
    };

    Slick.prototype.removeSlide = Slick.prototype.slickRemove = function(index, removeBefore, removeAll) {

        var _ = this;

        if (typeof(index) === 'boolean') {
            removeBefore = index;
            index = removeBefore === true ? 0 : _.slideCount - 1;
        } else {
            index = removeBefore === true ? --index : index;
        }

        if (_.slideCount < 1 || index < 0 || index > _.slideCount - 1) {
            return false;
        }

        _.unload();

        if (removeAll === true) {
            _.$slideTrack.children().remove();
        } else {
            _.$slideTrack.children(this.options.slide).eq(index).remove();
        }

        _.$slides = _.$slideTrack.children(this.options.slide);

        _.$slideTrack.children(this.options.slide).detach();

        _.$slideTrack.append(_.$slides);

        _.$slidesCache = _.$slides;

        _.reinit();

    };

    Slick.prototype.setCSS = function(position) {

        var _ = this,
            positionProps = {},
            x, y;

        if (_.options.rtl === true) {
            position = -position;
        }
        x = _.positionProp == 'left' ? Math.ceil(position) + 'px' : '0px';
        y = _.positionProp == 'top' ? Math.ceil(position) + 'px' : '0px';

        positionProps[_.positionProp] = position;

        if (_.transformsEnabled === false) {
            _.$slideTrack.css(positionProps);
        } else {
            positionProps = {};
            if (_.cssTransitions === false) {
                positionProps[_.animType] = 'translate(' + x + ', ' + y + ')';
                _.$slideTrack.css(positionProps);
            } else {
                positionProps[_.animType] = 'translate3d(' + x + ', ' + y + ', 0px)';
                _.$slideTrack.css(positionProps);
            }
        }

    };

    Slick.prototype.setDimensions = function() {

        var _ = this;

        if (_.options.vertical === false) {
            if (_.options.centerMode === true) {
                _.$list.css({
                    padding: ('0px ' + _.options.centerPadding)
                });
            }
        } else {
            _.$list.height(_.$slides.first().outerHeight(true) * _.options.slidesToShow);
            if (_.options.centerMode === true) {
                _.$list.css({
                    padding: (_.options.centerPadding + ' 0px')
                });
            }
        }

        _.listWidth = _.$list.width();
        _.listHeight = _.$list.height();


        if (_.options.vertical === false && _.options.variableWidth === false) {
            _.slideWidth = Math.ceil(_.listWidth / _.options.slidesToShow);
            _.$slideTrack.width(Math.ceil((_.slideWidth * _.$slideTrack.children('.slick-slide').length)));

        } else if (_.options.variableWidth === true) {
            _.$slideTrack.width(5000 * _.slideCount);
        } else {
            _.slideWidth = Math.ceil(_.listWidth);
            _.$slideTrack.height(Math.ceil((_.$slides.first().outerHeight(true) * _.$slideTrack.children('.slick-slide').length)));
        }

        var offset = _.$slides.first().outerWidth(true) - _.$slides.first().width();
        if (_.options.variableWidth === false) _.$slideTrack.children('.slick-slide').width(_.slideWidth - offset);

    };

    Slick.prototype.setFade = function() {

        var _ = this,
            targetLeft;

        _.$slides.each(function(index, element) {
            targetLeft = (_.slideWidth * index) * -1;
            if (_.options.rtl === true) {
                $(element).css({
                    position: 'relative',
                    right: targetLeft,
                    top: 0,
                    zIndex: _.options.zIndex - 2,
                    opacity: 0
                });
            } else {
                $(element).css({
                    position: 'relative',
                    left: targetLeft,
                    top: 0,
                    zIndex: _.options.zIndex - 2,
                    opacity: 0
                });
            }
        });

        _.$slides.eq(_.currentSlide).css({
            zIndex: _.options.zIndex - 1,
            opacity: 1
        });

    };

    Slick.prototype.setHeight = function() {

        var _ = this;

        if (_.options.slidesToShow === 1 && _.options.adaptiveHeight === true && _.options.vertical === false) {
            var targetHeight = _.$slides.eq(_.currentSlide).outerHeight(true);
            _.$list.css('height', targetHeight);
        }

    };

    Slick.prototype.setOption =
    Slick.prototype.slickSetOption = function() {

        /**
         * accepts arguments in format of:
         *
         *  - for changing a single option's value:
         *     .slick("setOption", option, value, refresh )
         *
         *  - for changing a set of responsive options:
         *     .slick("setOption", 'responsive', [{}, ...], refresh )
         *
         *  - for updating multiple values at once (not responsive)
         *     .slick("setOption", { 'option': value, ... }, refresh )
         */

        var _ = this, l, item, option, value, refresh = false, type;

        if( $.type( arguments[0] ) === 'object' ) {

            option =  arguments[0];
            refresh = arguments[1];
            type = 'multiple';

        } else if ( $.type( arguments[0] ) === 'string' ) {

            option =  arguments[0];
            value = arguments[1];
            refresh = arguments[2];

            if ( arguments[0] === 'responsive' && $.type( arguments[1] ) === 'array' ) {

                type = 'responsive';

            } else if ( typeof arguments[1] !== 'undefined' ) {

                type = 'single';

            }

        }

        if ( type === 'single' ) {

            _.options[option] = value;


        } else if ( type === 'multiple' ) {

            $.each( option , function( opt, val ) {

                _.options[opt] = val;

            });


        } else if ( type === 'responsive' ) {

            for ( item in value ) {

                if( $.type( _.options.responsive ) !== 'array' ) {

                    _.options.responsive = [ value[item] ];

                } else {

                    l = _.options.responsive.length-1;

                    // loop through the responsive object and splice out duplicates.
                    while( l >= 0 ) {

                        if( _.options.responsive[l].breakpoint === value[item].breakpoint ) {

                            _.options.responsive.splice(l,1);

                        }

                        l--;

                    }

                    _.options.responsive.push( value[item] );

                }

            }

        }

        if ( refresh ) {

            _.unload();
            _.reinit();

        }

    };

    Slick.prototype.setPosition = function() {

        var _ = this;

        _.setDimensions();

        _.setHeight();

        if (_.options.fade === false) {
            _.setCSS(_.getLeft(_.currentSlide));
        } else {
            _.setFade();
        }

        _.$slider.trigger('setPosition', [_]);

    };

    Slick.prototype.setProps = function() {

        var _ = this,
            bodyStyle = document.body.style;

        _.positionProp = _.options.vertical === true ? 'top' : 'left';

        if (_.positionProp === 'top') {
            _.$slider.addClass('slick-vertical');
        } else {
            _.$slider.removeClass('slick-vertical');
        }

        if (bodyStyle.WebkitTransition !== undefined ||
            bodyStyle.MozTransition !== undefined ||
            bodyStyle.msTransition !== undefined) {
            if (_.options.useCSS === true) {
                _.cssTransitions = true;
            }
        }

        if ( _.options.fade ) {
            if ( typeof _.options.zIndex === 'number' ) {
                if( _.options.zIndex < 3 ) {
                    _.options.zIndex = 3;
                }
            } else {
                _.options.zIndex = _.defaults.zIndex;
            }
        }

        if (bodyStyle.OTransform !== undefined) {
            _.animType = 'OTransform';
            _.transformType = '-o-transform';
            _.transitionType = 'OTransition';
            if (bodyStyle.perspectiveProperty === undefined && bodyStyle.webkitPerspective === undefined) _.animType = false;
        }
        if (bodyStyle.MozTransform !== undefined) {
            _.animType = 'MozTransform';
            _.transformType = '-moz-transform';
            _.transitionType = 'MozTransition';
            if (bodyStyle.perspectiveProperty === undefined && bodyStyle.MozPerspective === undefined) _.animType = false;
        }
        if (bodyStyle.webkitTransform !== undefined) {
            _.animType = 'webkitTransform';
            _.transformType = '-webkit-transform';
            _.transitionType = 'webkitTransition';
            if (bodyStyle.perspectiveProperty === undefined && bodyStyle.webkitPerspective === undefined) _.animType = false;
        }
        if (bodyStyle.msTransform !== undefined) {
            _.animType = 'msTransform';
            _.transformType = '-ms-transform';
            _.transitionType = 'msTransition';
            if (bodyStyle.msTransform === undefined) _.animType = false;
        }
        if (bodyStyle.transform !== undefined && _.animType !== false) {
            _.animType = 'transform';
            _.transformType = 'transform';
            _.transitionType = 'transition';
        }
        _.transformsEnabled = _.options.useTransform && (_.animType !== null && _.animType !== false);
    };


    Slick.prototype.setSlideClasses = function(index) {

        var _ = this,
            centerOffset, allSlides, indexOffset, remainder;

        allSlides = _.$slider
            .find('.slick-slide')
            .removeClass('slick-active slick-center slick-current')
            .attr('aria-hidden', 'true');

        _.$slides
            .eq(index)
            .addClass('slick-current');

        if (_.options.centerMode === true) {

            centerOffset = Math.floor(_.options.slidesToShow / 2);

            if (_.options.infinite === true) {

                if (index >= centerOffset && index <= (_.slideCount - 1) - centerOffset) {

                    _.$slides
                        .slice(index - centerOffset, index + centerOffset + 1)
                        .addClass('slick-active')
                        .attr('aria-hidden', 'false');

                } else {

                    indexOffset = _.options.slidesToShow + index;
                    allSlides
                        .slice(indexOffset - centerOffset + 1, indexOffset + centerOffset + 2)
                        .addClass('slick-active')
                        .attr('aria-hidden', 'false');

                }

                if (index === 0) {

                    allSlides
                        .eq(allSlides.length - 1 - _.options.slidesToShow)
                        .addClass('slick-center');

                } else if (index === _.slideCount - 1) {

                    allSlides
                        .eq(_.options.slidesToShow)
                        .addClass('slick-center');

                }

            }

            _.$slides
                .eq(index)
                .addClass('slick-center');

        } else {

            if (index >= 0 && index <= (_.slideCount - _.options.slidesToShow)) {

                _.$slides
                    .slice(index, index + _.options.slidesToShow)
                    .addClass('slick-active')
                    .attr('aria-hidden', 'false');

            } else if (allSlides.length <= _.options.slidesToShow) {

                allSlides
                    .addClass('slick-active')
                    .attr('aria-hidden', 'false');

            } else {

                remainder = _.slideCount % _.options.slidesToShow;
                indexOffset = _.options.infinite === true ? _.options.slidesToShow + index : index;

                if (_.options.slidesToShow == _.options.slidesToScroll && (_.slideCount - index) < _.options.slidesToShow) {

                    allSlides
                        .slice(indexOffset - (_.options.slidesToShow - remainder), indexOffset + remainder)
                        .addClass('slick-active')
                        .attr('aria-hidden', 'false');

                } else {

                    allSlides
                        .slice(indexOffset, indexOffset + _.options.slidesToShow)
                        .addClass('slick-active')
                        .attr('aria-hidden', 'false');

                }

            }

        }

        if (_.options.lazyLoad === 'ondemand') {
            _.lazyLoad();
        }

    };

    Slick.prototype.setupInfinite = function() {

        var _ = this,
            i, slideIndex, infiniteCount;

        if (_.options.fade === true) {
            _.options.centerMode = false;
        }

        if (_.options.infinite === true && _.options.fade === false) {

            slideIndex = null;

            if (_.slideCount > _.options.slidesToShow) {

                if (_.options.centerMode === true) {
                    infiniteCount = _.options.slidesToShow + 1;
                } else {
                    infiniteCount = _.options.slidesToShow;
                }

                for (i = _.slideCount; i > (_.slideCount -
                        infiniteCount); i -= 1) {
                    slideIndex = i - 1;
                    $(_.$slides[slideIndex]).clone(true).attr('id', '')
                        .attr('data-slick-index', slideIndex - _.slideCount)
                        .prependTo(_.$slideTrack).addClass('slick-cloned');
                }
                for (i = 0; i < infiniteCount; i += 1) {
                    slideIndex = i;
                    $(_.$slides[slideIndex]).clone(true).attr('id', '')
                        .attr('data-slick-index', slideIndex + _.slideCount)
                        .appendTo(_.$slideTrack).addClass('slick-cloned');
                }
                _.$slideTrack.find('.slick-cloned').find('[id]').each(function() {
                    $(this).attr('id', '');
                });

            }

        }

    };

    Slick.prototype.interrupt = function( toggle ) {

        var _ = this;

        if( !toggle ) {
            _.autoPlay();
        }
        _.interrupted = toggle;

    };

    Slick.prototype.selectHandler = function(event) {

        var _ = this;

        var targetElement =
            $(event.target).is('.slick-slide') ?
                $(event.target) :
                $(event.target).parents('.slick-slide');

        var index = parseInt(targetElement.attr('data-slick-index'));

        if (!index) index = 0;

        if (_.slideCount <= _.options.slidesToShow) {

            _.setSlideClasses(index);
            _.asNavFor(index);
            return;

        }

        _.slideHandler(index);

    };

    Slick.prototype.slideHandler = function(index, sync, dontAnimate) {

        var targetSlide, animSlide, oldSlide, slideLeft, targetLeft = null,
            _ = this, navTarget;

        sync = sync || false;

        if (_.animating === true && _.options.waitForAnimate === true) {
            return;
        }

        if (_.options.fade === true && _.currentSlide === index) {
            return;
        }

        // if (_.slideCount <= _.options.slidesToShow) {
        //     return;
        // }

        if (sync === false) {
            _.asNavFor(index);
        }

        targetSlide = index;
        targetLeft = _.getLeft(targetSlide);
        slideLeft = _.getLeft(_.currentSlide);

        _.currentLeft = _.swipeLeft === null ? slideLeft : _.swipeLeft;

        if (_.options.infinite === false && _.options.centerMode === false && (index < 0 || index > _.getDotCount() * _.options.slidesToScroll)) {
            if (_.options.fade === false) {
                targetSlide = _.currentSlide;
                if (dontAnimate !== true) {
                    _.animateSlide(slideLeft, function() {
                        _.postSlide(targetSlide);
                    });
                } else {
                    _.postSlide(targetSlide);
                }
            }
            return;
        } else if (_.options.infinite === false && _.options.centerMode === true && (index < 0 || index > (_.slideCount - _.options.slidesToScroll))) {
            if (_.options.fade === false) {
                targetSlide = _.currentSlide;
                if (dontAnimate !== true) {
                    _.animateSlide(slideLeft, function() {
                        _.postSlide(targetSlide);
                    });
                } else {
                    _.postSlide(targetSlide);
                }
            }
            return;
        }

        if ( _.options.autoplay ) {
            clearInterval(_.autoPlayTimer);
        }

        if (targetSlide < 0) {
            if (_.slideCount % _.options.slidesToScroll !== 0) {
                animSlide = _.slideCount - (_.slideCount % _.options.slidesToScroll);
            } else {
                animSlide = _.slideCount + targetSlide;
            }
        } else if (targetSlide >= _.slideCount) {
            if (_.slideCount % _.options.slidesToScroll !== 0) {
                animSlide = 0;
            } else {
                animSlide = targetSlide - _.slideCount;
            }
        } else {
            animSlide = targetSlide;
        }

        _.animating = true;

        _.$slider.trigger('beforeChange', [_, _.currentSlide, animSlide]);

        oldSlide = _.currentSlide;
        _.currentSlide = animSlide;

        _.setSlideClasses(_.currentSlide);

        if ( _.options.asNavFor ) {

            navTarget = _.getNavTarget();
            navTarget = navTarget.slick('getSlick');

            if ( navTarget.slideCount <= navTarget.options.slidesToShow ) {
                navTarget.setSlideClasses(_.currentSlide);
            }

        }

        _.updateDots();
        _.updateArrows();

        if (_.options.fade === true) {
            if (dontAnimate !== true) {

                _.fadeSlideOut(oldSlide);

                _.fadeSlide(animSlide, function() {
                    _.postSlide(animSlide);
                });

            } else {
                _.postSlide(animSlide);
            }
            _.animateHeight();
            return;
        }

        if (dontAnimate !== true) {
            _.animateSlide(targetLeft, function() {
                _.postSlide(animSlide);
            });
        } else {
            _.postSlide(animSlide);
        }

    };

    Slick.prototype.startLoad = function() {

        var _ = this;

        if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) {

            _.$prevArrow.hide();
            _.$nextArrow.hide();

        }

        if (_.options.dots === true && _.slideCount > _.options.slidesToShow) {

            _.$dots.hide();

        }

        _.$slider.addClass('slick-loading');

    };

    Slick.prototype.swipeDirection = function() {

        var xDist, yDist, r, swipeAngle, _ = this;

        xDist = _.touchObject.startX - _.touchObject.curX;
        yDist = _.touchObject.startY - _.touchObject.curY;
        r = Math.atan2(yDist, xDist);

        swipeAngle = Math.round(r * 180 / Math.PI);
        if (swipeAngle < 0) {
            swipeAngle = 360 - Math.abs(swipeAngle);
        }

        if ((swipeAngle <= 45) && (swipeAngle >= 0)) {
            return (_.options.rtl === false ? 'left' : 'right');
        }
        if ((swipeAngle <= 360) && (swipeAngle >= 315)) {
            return (_.options.rtl === false ? 'left' : 'right');
        }
        if ((swipeAngle >= 135) && (swipeAngle <= 225)) {
            return (_.options.rtl === false ? 'right' : 'left');
        }
        if (_.options.verticalSwiping === true) {
            if ((swipeAngle >= 35) && (swipeAngle <= 135)) {
                return 'down';
            } else {
                return 'up';
            }
        }

        return 'vertical';

    };

    Slick.prototype.swipeEnd = function(event) {

        var _ = this,
            slideCount,
            direction;

        _.dragging = false;
        _.interrupted = false;
        _.shouldClick = ( _.touchObject.swipeLength > 10 ) ? false : true;

        if ( _.touchObject.curX === undefined ) {
            return false;
        }

        if ( _.touchObject.edgeHit === true ) {
            _.$slider.trigger('edge', [_, _.swipeDirection() ]);
        }

        if ( _.touchObject.swipeLength >= _.touchObject.minSwipe ) {

            direction = _.swipeDirection();

            switch ( direction ) {

                case 'left':
                case 'down':

                    slideCount =
                        _.options.swipeToSlide ?
                            _.checkNavigable( _.currentSlide + _.getSlideCount() ) :
                            _.currentSlide + _.getSlideCount();

                    _.currentDirection = 0;

                    break;

                case 'right':
                case 'up':

                    slideCount =
                        _.options.swipeToSlide ?
                            _.checkNavigable( _.currentSlide - _.getSlideCount() ) :
                            _.currentSlide - _.getSlideCount();

                    _.currentDirection = 1;

                    break;

                default:


            }

            if( direction != 'vertical' ) {

                _.slideHandler( slideCount );
                _.touchObject = {};
                _.$slider.trigger('swipe', [_, direction ]);

            }

        } else {

            if ( _.touchObject.startX !== _.touchObject.curX ) {

                _.slideHandler( _.currentSlide );
                _.touchObject = {};

            }

        }

    };

    Slick.prototype.swipeHandler = function(event) {

        var _ = this;

        if ((_.options.swipe === false) || ('ontouchend' in document && _.options.swipe === false)) {
            return;
        } else if (_.options.draggable === false && event.type.indexOf('mouse') !== -1) {
            return;
        }

        _.touchObject.fingerCount = event.originalEvent && event.originalEvent.touches !== undefined ?
            event.originalEvent.touches.length : 1;

        _.touchObject.minSwipe = _.listWidth / _.options
            .touchThreshold;

        if (_.options.verticalSwiping === true) {
            _.touchObject.minSwipe = _.listHeight / _.options
                .touchThreshold;
        }

        switch (event.data.action) {

            case 'start':
                _.swipeStart(event);
                break;

            case 'move':
                _.swipeMove(event);
                break;

            case 'end':
                _.swipeEnd(event);
                break;

        }

    };

    Slick.prototype.swipeMove = function(event) {

        var _ = this,
            edgeWasHit = false,
            curLeft, swipeDirection, swipeLength, positionOffset, touches;

        touches = event.originalEvent !== undefined ? event.originalEvent.touches : null;

        if (!_.dragging || touches && touches.length !== 1) {
            return false;
        }

        curLeft = _.getLeft(_.currentSlide);

        _.touchObject.curX = touches !== undefined ? touches[0].pageX : event.clientX;
        _.touchObject.curY = touches !== undefined ? touches[0].pageY : event.clientY;

        _.touchObject.swipeLength = Math.round(Math.sqrt(
            Math.pow(_.touchObject.curX - _.touchObject.startX, 2)));

        if (_.options.verticalSwiping === true) {
            _.touchObject.swipeLength = Math.round(Math.sqrt(
                Math.pow(_.touchObject.curY - _.touchObject.startY, 2)));
        }

        swipeDirection = _.swipeDirection();

        if (swipeDirection === 'vertical') {
            return;
        }

        if (event.originalEvent !== undefined && _.touchObject.swipeLength > 4) {
            event.preventDefault();
        }

        positionOffset = (_.options.rtl === false ? 1 : -1) * (_.touchObject.curX > _.touchObject.startX ? 1 : -1);
        if (_.options.verticalSwiping === true) {
            positionOffset = _.touchObject.curY > _.touchObject.startY ? 1 : -1;
        }


        swipeLength = _.touchObject.swipeLength;

        _.touchObject.edgeHit = false;

        if (_.options.infinite === false) {
            if ((_.currentSlide === 0 && swipeDirection === 'right') || (_.currentSlide >= _.getDotCount() && swipeDirection === 'left')) {
                swipeLength = _.touchObject.swipeLength * _.options.edgeFriction;
                _.touchObject.edgeHit = true;
            }
        }

        if (_.options.vertical === false) {
            _.swipeLeft = curLeft + swipeLength * positionOffset;
        } else {
            _.swipeLeft = curLeft + (swipeLength * (_.$list.height() / _.listWidth)) * positionOffset;
        }
        if (_.options.verticalSwiping === true) {
            _.swipeLeft = curLeft + swipeLength * positionOffset;
        }

        if (_.options.fade === true || _.options.touchMove === false) {
            return false;
        }

        if (_.animating === true) {
            _.swipeLeft = null;
            return false;
        }

        _.setCSS(_.swipeLeft);

    };

    Slick.prototype.swipeStart = function(event) {

        var _ = this,
            touches;

        _.interrupted = true;

        if (_.touchObject.fingerCount !== 1 || _.slideCount < _.options.slidesToShow) {
            _.touchObject = {};
            return false;
        }

        if (event.originalEvent !== undefined && event.originalEvent.touches !== undefined) {
            touches = event.originalEvent.touches[0];
        }

        _.touchObject.startX = _.touchObject.curX = touches !== undefined ? touches.pageX : event.clientX;
        _.touchObject.startY = _.touchObject.curY = touches !== undefined ? touches.pageY : event.clientY;

        _.dragging = true;

    };

    Slick.prototype.unfilterSlides = Slick.prototype.slickUnfilter = function() {

        var _ = this;

        if (_.$slidesCache !== null) {

            _.unload();

            _.$slideTrack.children(this.options.slide).detach();

            _.$slidesCache.appendTo(_.$slideTrack);

            _.reinit();

        }

    };

    Slick.prototype.unload = function() {

        var _ = this;

        $('.slick-cloned', _.$slider).remove();

        if (_.$dots) {
            _.$dots.remove();
        }

        if (_.$prevArrow && _.htmlExpr.test(_.options.prevArrow)) {
            _.$prevArrow.remove();
        }

        if (_.$nextArrow && _.htmlExpr.test(_.options.nextArrow)) {
            _.$nextArrow.remove();
        }

        _.$slides
            .removeClass('slick-slide slick-active slick-visible slick-current')
            .attr('aria-hidden', 'true')
            .css('width', '');

    };

    Slick.prototype.unslick = function(fromBreakpoint) {

        var _ = this;
        _.$slider.trigger('unslick', [_, fromBreakpoint]);
        _.destroy();

    };

    Slick.prototype.updateArrows = function() {

        var _ = this,
            centerOffset;

        centerOffset = Math.floor(_.options.slidesToShow / 2);

        if ( _.options.arrows === true &&
            _.slideCount > _.options.slidesToShow &&
            !_.options.infinite ) {

            _.$prevArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');
            _.$nextArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');

            if (_.currentSlide === 0) {

                _.$prevArrow.addClass('slick-disabled').attr('aria-disabled', 'true');
                _.$nextArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');

            } else if (_.currentSlide >= _.slideCount - _.options.slidesToShow && _.options.centerMode === false) {

                _.$nextArrow.addClass('slick-disabled').attr('aria-disabled', 'true');
                _.$prevArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');

            } else if (_.currentSlide >= _.slideCount - 1 && _.options.centerMode === true) {

                _.$nextArrow.addClass('slick-disabled').attr('aria-disabled', 'true');
                _.$prevArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');

            }

        }

    };

    Slick.prototype.updateDots = function() {

        var _ = this;

        if (_.$dots !== null) {

            _.$dots
                .find('li')
                .removeClass('slick-active')
                .attr('aria-hidden', 'true');

            _.$dots
                .find('li')
                .eq(Math.floor(_.currentSlide / _.options.slidesToScroll))
                .addClass('slick-active')
                .attr('aria-hidden', 'false');

        }

    };

    Slick.prototype.visibility = function() {

        var _ = this;

        if ( _.options.autoplay ) {

            if ( document[_.hidden] ) {

                _.interrupted = true;

            } else {

                _.interrupted = false;

            }

        }

    };

    $.fn.slick = function() {
        var _ = this,
            opt = arguments[0],
            args = Array.prototype.slice.call(arguments, 1),
            l = _.length,
            i,
            ret;
        for (i = 0; i < l; i++) {
            if (typeof opt == 'object' || typeof opt == 'undefined')
                _[i].slick = new Slick(_[i], opt);
            else
                ret = _[i].slick[opt].apply(_[i].slick, args);
            if (typeof ret != 'undefined') return ret;
        }
        return _;
    };

}));;
/*
 * jQuery throttle / debounce - v1.1 - 3/7/2010
 * http://benalman.com/projects/jquery-throttle-debounce-plugin/
 * 
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function(b,c){var $=b.jQuery||b.Cowboy||(b.Cowboy={}),a;$.throttle=a=function(e,f,j,i){var h,d=0;if(typeof f!=="boolean"){i=j;j=f;f=c}function g(){var o=this,m=+new Date()-d,n=arguments;function l(){d=+new Date();j.apply(o,n)}function k(){h=c}if(i&&!h){l()}h&&clearTimeout(h);if(i===c&&m>e){l()}else{if(f!==true){h=setTimeout(i?k:l,i===c?e-m:e)}}}if($.guid){g.guid=j.guid=j.guid||$.guid++}return g};$.debounce=function(d,e,f){return f===c?a(d,e,false):a(d,f,e!==false)}})(this);;
!function(a){function c(){}function d(a){function d(b){b.prototype.option||(b.prototype.option=function(b){a.isPlainObject(b)&&(this.options=a.extend(!0,this.options,b))})}function f(c,d){a.fn[c]=function(f){if("string"==typeof f){for(var g=b.call(arguments,1),h=0,i=this.length;h<i;h++){var j=this[h],k=a.data(j,c);if(k)if(a.isFunction(k[f])&&"_"!==f.charAt(0)){var l=k[f].apply(k,g);if(void 0!==l)return l}else e("no such method '"+f+"' for "+c+" instance");else e("cannot call methods on "+c+" prior to initialization; attempted to call '"+f+"'")}return this}return this.each(function(){var b=a.data(this,c);b?(b.option(f),b._init()):(b=new d(this,f),a.data(this,c,b))})}}if(a){var e="undefined"==typeof console?c:function(a){console.error(a)};return a.bridget=function(a,b){d(b),f(a,b)},a.bridget}}var b=Array.prototype.slice;"function"==typeof define&&define.amd?define("jquery-bridget/jquery.bridget",["jquery"],d):d("object"==typeof exports?require("jquery"):a.jQuery)}(window),function(a){function b(a){return new RegExp("(^|\\s+)"+a+"(\\s+|$)")}function f(a,b){var f=c(a,b)?e:d;f(a,b)}var c,d,e;"classList"in document.documentElement?(c=function(a,b){return a.classList.contains(b)},d=function(a,b){a.classList.add(b)},e=function(a,b){a.classList.remove(b)}):(c=function(a,c){return b(c).test(a.className)},d=function(a,b){c(a,b)||(a.className=a.className+" "+b)},e=function(a,c){a.className=a.className.replace(b(c)," ")});var g={hasClass:c,addClass:d,removeClass:e,toggleClass:f,has:c,add:d,remove:e,toggle:f};"function"==typeof define&&define.amd?define("classie/classie",g):"object"==typeof exports?module.exports=g:a.classie=g}(window),function(){"use strict";function a(){}function e(a,b){for(var c=a.length;c--;)if(a[c].listener===b)return c;return-1}function f(a){return function(){return this[a].apply(this,arguments)}}var b=a.prototype,c=this,d=c.EventEmitter;b.getListeners=function(b){var d,e,c=this._getEvents();if(b instanceof RegExp){d={};for(e in c)c.hasOwnProperty(e)&&b.test(e)&&(d[e]=c[e])}else d=c[b]||(c[b]=[]);return d},b.flattenListeners=function(b){var d,c=[];for(d=0;d<b.length;d+=1)c.push(b[d].listener);return c},b.getListenersAsObject=function(b){var d,c=this.getListeners(b);return c instanceof Array&&(d={},d[b]=c),d||c},b.addListener=function(b,c){var g,d=this.getListenersAsObject(b),f="object"==typeof c;for(g in d)d.hasOwnProperty(g)&&e(d[g],c)===-1&&d[g].push(f?c:{listener:c,once:!1});return this},b.on=f("addListener"),b.addOnceListener=function(b,c){return this.addListener(b,{listener:c,once:!0})},b.once=f("addOnceListener"),b.defineEvent=function(b){return this.getListeners(b),this},b.defineEvents=function(b){for(var c=0;c<b.length;c+=1)this.defineEvent(b[c]);return this},b.removeListener=function(b,c){var f,g,d=this.getListenersAsObject(b);for(g in d)d.hasOwnProperty(g)&&(f=e(d[g],c),f!==-1&&d[g].splice(f,1));return this},b.off=f("removeListener"),b.addListeners=function(b,c){return this.manipulateListeners(!1,b,c)},b.removeListeners=function(b,c){return this.manipulateListeners(!0,b,c)},b.manipulateListeners=function(b,c,d){var e,f,g=b?this.removeListener:this.addListener,h=b?this.removeListeners:this.addListeners;if("object"!=typeof c||c instanceof RegExp)for(e=d.length;e--;)g.call(this,c,d[e]);else for(e in c)c.hasOwnProperty(e)&&(f=c[e])&&("function"==typeof f?g.call(this,e,f):h.call(this,e,f));return this},b.removeEvent=function(b){var e,c=typeof b,d=this._getEvents();if("string"===c)delete d[b];else if(b instanceof RegExp)for(e in d)d.hasOwnProperty(e)&&b.test(e)&&delete d[e];else delete this._events;return this},b.removeAllListeners=f("removeEvent"),b.emitEvent=function(b,c){var e,f,g,h,d=this.getListenersAsObject(b);for(g in d)if(d.hasOwnProperty(g))for(f=d[g].length;f--;)e=d[g][f],e.once===!0&&this.removeListener(b,e.listener),h=e.listener.apply(this,c||[]),h===this._getOnceReturnValue()&&this.removeListener(b,e.listener);return this},b.trigger=f("emitEvent"),b.emit=function(b){var c=Array.prototype.slice.call(arguments,1);return this.emitEvent(b,c)},b.setOnceReturnValue=function(b){return this._onceReturnValue=b,this},b._getOnceReturnValue=function(){return!this.hasOwnProperty("_onceReturnValue")||this._onceReturnValue},b._getEvents=function(){return this._events||(this._events={})},a.noConflict=function(){return c.EventEmitter=d,a},"function"==typeof define&&define.amd?define("eventEmitter/EventEmitter",[],function(){return a}):"object"==typeof module&&module.exports?module.exports=a:c.EventEmitter=a}.call(this),function(a){function d(b){var c=a.event;return c.target=c.target||c.srcElement||b,c}var b=document.documentElement,c=function(){};b.addEventListener?c=function(a,b,c){a.addEventListener(b,c,!1)}:b.attachEvent&&(c=function(a,b,c){a[b+c]=c.handleEvent?function(){var b=d(a);c.handleEvent.call(c,b)}:function(){var b=d(a);c.call(a,b)},a.attachEvent("on"+b,a[b+c])});var e=function(){};b.removeEventListener?e=function(a,b,c){a.removeEventListener(b,c,!1)}:b.detachEvent&&(e=function(a,b,c){a.detachEvent("on"+b,a[b+c]);try{delete a[b+c]}catch(d){a[b+c]=void 0}});var f={bind:c,unbind:e};"function"==typeof define&&define.amd?define("eventie/eventie",f):"object"==typeof exports?module.exports=f:a.eventie=f}(window),function(a){function d(a){if(a){if("string"==typeof c[a])return a;a=a.charAt(0).toUpperCase()+a.slice(1);for(var d,e=0,f=b.length;e<f;e++)if(d=b[e]+a,"string"==typeof c[d])return d}}var b="Webkit Moz ms Ms O".split(" "),c=document.documentElement.style;"function"==typeof define&&define.amd?define("get-style-property/get-style-property",[],function(){return d}):"object"==typeof exports?module.exports=d:a.getStyleProperty=d}(window),function(a,b){function c(a){var b=parseFloat(a),c=a.indexOf("%")===-1&&!isNaN(b);return c&&b}function d(){}function g(){for(var a={width:0,height:0,innerWidth:0,innerHeight:0,outerWidth:0,outerHeight:0},b=0,c=f.length;b<c;b++){var d=f[b];a[d]=0}return a}function h(b){function k(){if(!d){d=!0;var f=a.getComputedStyle;if(h=function(){var a=f?function(a){return f(a,null)}:function(a){return a.currentStyle};return function(c){var d=a(c);return d||e("Style returned "+d+". Are you running this code in a hidden iframe on Firefox? See http://bit.ly/getsizebug1"),d}}(),i=b("boxSizing")){var g=document.createElement("div");g.style.width="200px",g.style.padding="1px 2px 3px 4px",g.style.borderStyle="solid",g.style.borderWidth="1px 2px 3px 4px",g.style[i]="border-box";var k=document.body||document.documentElement;k.appendChild(g);var l=h(g);j=200===c(l.width),k.removeChild(g)}}}function l(a){if(k(),"string"==typeof a&&(a=document.querySelector(a)),a&&"object"==typeof a&&a.nodeType){var b=h(a);if("none"===b.display)return g();var d={};d.width=a.offsetWidth,d.height=a.offsetHeight;for(var e=d.isBorderBox=!(!i||!b[i]||"border-box"!==b[i]),l=0,n=f.length;l<n;l++){var o=f[l],p=b[o];p=m(a,p);var q=parseFloat(p);d[o]=isNaN(q)?0:q}var r=d.paddingLeft+d.paddingRight,s=d.paddingTop+d.paddingBottom,t=d.marginLeft+d.marginRight,u=d.marginTop+d.marginBottom,v=d.borderLeftWidth+d.borderRightWidth,w=d.borderTopWidth+d.borderBottomWidth,x=e&&j,y=c(b.width);y!==!1&&(d.width=y+(x?0:r+v));var z=c(b.height);return z!==!1&&(d.height=z+(x?0:s+w)),d.innerWidth=d.width-(r+v),d.innerHeight=d.height-(s+w),d.outerWidth=d.width+t,d.outerHeight=d.height+u,d}}function m(b,c){if(a.getComputedStyle||c.indexOf("%")===-1)return c;var d=b.style,e=d.left,f=b.runtimeStyle,g=f&&f.left;return g&&(f.left=b.currentStyle.left),d.left=c,c=d.pixelLeft,d.left=e,g&&(f.left=g),c}var h,i,j,d=!1;return l}var e="undefined"==typeof console?d:function(a){console.error(a)},f=["paddingLeft","paddingRight","paddingTop","paddingBottom","marginLeft","marginRight","marginTop","marginBottom","borderLeftWidth","borderRightWidth","borderTopWidth","borderBottomWidth"];"function"==typeof define&&define.amd?define("get-size/get-size",["get-style-property/get-style-property"],h):"object"==typeof exports?module.exports=h(require("desandro-get-style-property")):a.getSize=h(a.getStyleProperty)}(window),function(a){function d(a){"function"==typeof a&&(d.isReady?a():c.push(a))}function e(a){var c="readystatechange"===a.type&&"complete"!==b.readyState;d.isReady||c||f()}function f(){d.isReady=!0;for(var a=0,b=c.length;a<b;a++){var e=c[a];e()}}function g(c){return"complete"===b.readyState?f():(c.bind(b,"DOMContentLoaded",e),c.bind(b,"readystatechange",e),c.bind(a,"load",e)),d}var b=a.document,c=[];d.isReady=!1,"function"==typeof define&&define.amd?define("doc-ready/doc-ready",["eventie/eventie"],g):"object"==typeof exports?module.exports=g(require("eventie")):a.docReady=g(a.eventie)}(window),function(a){"use strict";function c(a,c){return a[b](c)}function d(a){if(!a.parentNode){var b=document.createDocumentFragment();b.appendChild(a)}}function e(a,b){d(a);for(var c=a.parentNode.querySelectorAll(b),e=0,f=c.length;e<f;e++)if(c[e]===a)return!0;return!1}function f(a,b){return d(a),c(a,b)}var g,b=function(){if(a.matches)return"matches";if(a.matchesSelector)return"matchesSelector";for(var b=["webkit","moz","ms","o"],c=0,d=b.length;c<d;c++){var e=b[c],f=e+"MatchesSelector";if(a[f])return f}}();if(b){var h=document.createElement("div"),i=c(h,"div");g=i?c:f}else g=e;"function"==typeof define&&define.amd?define("matches-selector/matches-selector",[],function(){return g}):"object"==typeof exports?module.exports=g:window.matchesSelector=g}(Element.prototype),function(a,b){"use strict";"function"==typeof define&&define.amd?define("fizzy-ui-utils/utils",["doc-ready/doc-ready","matches-selector/matches-selector"],function(c,d){return b(a,c,d)}):"object"==typeof exports?module.exports=b(a,require("doc-ready"),require("desandro-matches-selector")):a.fizzyUIUtils=b(a,a.docReady,a.matchesSelector)}(window,function(b,c,d){var e={};e.extend=function(a,b){for(var c in b)a[c]=b[c];return a},e.modulo=function(a,b){return(a%b+b)%b};var f=Object.prototype.toString;e.isArray=function(a){return"[object Array]"==f.call(a)},e.makeArray=function(a){var b=[];if(e.isArray(a))b=a;else if(a&&"number"==typeof a.length)for(var c=0,d=a.length;c<d;c++)b.push(a[c]);else b.push(a);return b},e.indexOf=Array.prototype.indexOf?function(a,b){return a.indexOf(b)}:function(a,b){for(var c=0,d=a.length;c<d;c++)if(a[c]===b)return c;return-1},e.removeFrom=function(a,b){var c=e.indexOf(a,b);c!=-1&&a.splice(c,1)},e.isElement="function"==typeof HTMLElement||"object"==typeof HTMLElement?function(b){return b instanceof HTMLElement}:function(b){return b&&"object"==typeof b&&1==b.nodeType&&"string"==typeof b.nodeName},e.setText=function(){function b(b,c){a=a||(void 0!==document.documentElement.textContent?"textContent":"innerText"),b[a]=c}var a;return b}(),e.getParent=function(a,b){for(;a!=document.body;)if(a=a.parentNode,d(a,b))return a},e.getQueryElement=function(a){return"string"==typeof a?document.querySelector(a):a},e.handleEvent=function(a){var b="on"+a.type;this[b]&&this[b](a)},e.filterFindElements=function(a,b){a=e.makeArray(a);for(var c=[],f=0,g=a.length;f<g;f++){var h=a[f];if(e.isElement(h))if(b){d(h,b)&&c.push(h);for(var i=h.querySelectorAll(b),j=0,k=i.length;j<k;j++)c.push(i[j])}else c.push(h)}return c},e.debounceMethod=function(a,b,c){var d=a.prototype[b],e=b+"Timeout";a.prototype[b]=function(){var a=this[e];a&&clearTimeout(a);var b=arguments,f=this;this[e]=setTimeout(function(){d.apply(f,b),delete f[e]},c||100)}},e.toDashed=function(a){return a.replace(/(.)([A-Z])/g,function(a,b,c){return b+"-"+c}).toLowerCase()};var g=b.console;return e.htmlInit=function(a,d){c(function(){for(var c=e.toDashed(d),f=document.querySelectorAll(".js-"+c),h="data-"+c+"-options",i=0,j=f.length;i<j;i++){var m,k=f[i],l=k.getAttribute(h);try{m=l&&JSON.parse(l)}catch(a){g&&g.error("Error parsing "+h+" on "+k.nodeName.toLowerCase()+(k.id?"#"+k.id:"")+": "+a);continue}var n=new a(k,m),o=b.jQuery;o&&o.data(k,d,n)}})},e}),function(a,b){"use strict";"function"==typeof define&&define.amd?define("flickity/js/cell",["get-size/get-size"],function(c){return b(a,c)}):"object"==typeof exports?module.exports=b(a,require("get-size")):(a.Flickity=a.Flickity||{},a.Flickity.Cell=b(a,a.getSize))}(window,function(b,c){function d(a,b){this.element=a,this.parent=b,this.create()}var e="attachEvent"in b;return d.prototype.create=function(){this.element.style.position="absolute",e&&this.element.setAttribute("unselectable","on"),this.x=0,this.shift=0},d.prototype.destroy=function(){this.element.style.position="";var a=this.parent.originSide;this.element.style[a]=""},d.prototype.getSize=function(){this.size=c(this.element)},d.prototype.setPosition=function(a){this.x=a,this.setDefaultTarget(),this.renderPosition(a)},d.prototype.setDefaultTarget=function(){var a="left"==this.parent.originSide?"marginLeft":"marginRight";this.target=this.x+this.size[a]+this.size.width*this.parent.cellAlign},d.prototype.renderPosition=function(a){var b=this.parent.originSide;this.element.style[b]=this.parent.getPositionValue(a)},d.prototype.wrapShift=function(a){this.shift=a,this.renderPosition(this.x+this.parent.slideableWidth*a)},d.prototype.remove=function(){this.element.parentNode.removeChild(this.element)},d}),function(a,b){"use strict";"function"==typeof define&&define.amd?define("flickity/js/animate",["get-style-property/get-style-property","fizzy-ui-utils/utils"],function(c,d){return b(a,c,d)}):"object"==typeof exports?module.exports=b(a,require("desandro-get-style-property"),require("fizzy-ui-utils")):(a.Flickity=a.Flickity||{},a.Flickity.animatePrototype=b(a,a.getStyleProperty,a.fizzyUIUtils))}(window,function(b,c,d){for(var i,e=0,f="webkit moz ms o".split(" "),g=b.requestAnimationFrame,h=b.cancelAnimationFrame,j=0;j<f.length&&(!g||!h);j++)i=f[j],g=g||b[i+"RequestAnimationFrame"],h=h||b[i+"CancelAnimationFrame"]||b[i+"CancelRequestAnimationFrame"];g&&h||(g=function(a){var c=(new Date).getTime(),d=Math.max(0,16-(c-e)),f=b.setTimeout(function(){a(c+d)},d);return e=c+d,f},h=function(a){b.clearTimeout(a)});var k={};k.startAnimation=function(){this.isAnimating||(this.isAnimating=!0,this.restingFrames=0,this.animate())},k.animate=function(){this.applyDragForce(),this.applySelectedAttraction();var a=this.x;if(this.integratePhysics(),this.positionSlider(),this.settle(a),this.isAnimating){var b=this;g(function(){b.animate()})}};var l=c("transform"),m=!!c("perspective");return k.positionSlider=function(){var a=this.x;this.options.wrapAround&&this.cells.length>1&&(a=d.modulo(a,this.slideableWidth),a-=this.slideableWidth,this.shiftWrapCells(a)),a+=this.cursorPosition,a=this.options.rightToLeft&&l?-a:a;var b=this.getPositionValue(a);l?this.slider.style[l]=m&&this.isAnimating?"translate3d("+b+",0,0)":"translateX("+b+")":this.slider.style[this.originSide]=b},k.positionSliderAtSelected=function(){if(this.cells.length){var a=this.cells[this.selectedIndex];this.x=-a.target,this.positionSlider()}},k.getPositionValue=function(a){return this.options.percentPosition?.01*Math.round(a/this.size.innerWidth*1e4)+"%":Math.round(a)+"px"},k.settle=function(a){this.isPointerDown||Math.round(100*this.x)!=Math.round(100*a)||this.restingFrames++,this.restingFrames>2&&(this.isAnimating=!1,delete this.isFreeScrolling,m&&this.positionSlider(),this.dispatchEvent("settle"))},k.shiftWrapCells=function(a){var b=this.cursorPosition+a;this._shiftCells(this.beforeShiftCells,b,-1);var c=this.size.innerWidth-(a+this.slideableWidth+this.cursorPosition);this._shiftCells(this.afterShiftCells,c,1)},k._shiftCells=function(a,b,c){for(var d=0,e=a.length;d<e;d++){var f=a[d],g=b>0?c:0;f.wrapShift(g),b-=f.size.outerWidth}},k._unshiftCells=function(a){if(a&&a.length)for(var b=0,c=a.length;b<c;b++)a[b].wrapShift(0)},k.integratePhysics=function(){this.velocity+=this.accel,this.x+=this.velocity,this.velocity*=this.getFrictionFactor(),this.accel=0},k.applyForce=function(a){this.accel+=a},k.getFrictionFactor=function(){return 1-this.options[this.isFreeScrolling?"freeScrollFriction":"friction"]},k.getRestingPosition=function(){return this.x+this.velocity/(1-this.getFrictionFactor())},k.applyDragForce=function(){if(this.isPointerDown){var a=this.dragX-this.x,b=a-this.velocity;this.applyForce(b)}},k.applySelectedAttraction=function(){var a=this.cells.length;if(!this.isPointerDown&&!this.isFreeScrolling&&a){var b=this.cells[this.selectedIndex],c=this.options.wrapAround&&a>1?this.slideableWidth*Math.floor(this.selectedIndex/a):0,d=(b.target+c)*-1-this.x,e=d*this.options.selectedAttraction;this.applyForce(e)}},k}),function(a,b){"use strict";if("function"==typeof define&&define.amd)define("flickity/js/flickity",["classie/classie","eventEmitter/EventEmitter","eventie/eventie","get-size/get-size","fizzy-ui-utils/utils","./cell","./animate"],function(c,d,e,f,g,h,i){return b(a,c,d,e,f,g,h,i)});else if("object"==typeof exports)module.exports=b(a,require("desandro-classie"),require("wolfy87-eventemitter"),require("eventie"),require("get-size"),require("fizzy-ui-utils"),require("./cell"),require("./animate"));else{var c=a.Flickity;a.Flickity=b(a,a.classie,a.EventEmitter,a.eventie,a.getSize,a.fizzyUIUtils,c.Cell,c.animatePrototype)}}(window,function(b,c,d,e,f,g,h,i){function m(a,b){for(a=g.makeArray(a);a.length;)b.appendChild(a.shift())}function p(a,b){var c=g.getQueryElement(a);return c?(this.element=c,j&&(this.$element=j(this.element)),this.options=g.extend({},this.constructor.defaults),this.option(b),void this._create()):void(l&&l.error("Bad element for Flickity: "+(c||a)))}var j=b.jQuery,k=b.getComputedStyle,l=b.console,n=0,o={};p.defaults={accessibility:!0,cellAlign:"center",freeScrollFriction:.075,friction:.28,percentPosition:!0,resize:!0,selectedAttraction:.025,setGallerySize:!0},p.createMethods=[],g.extend(p.prototype,d.prototype),p.prototype._create=function(){var a=this.guid=++n;this.element.flickityGUID=a,o[a]=this,this.selectedIndex=0,this.restingFrames=0,this.x=0,this.velocity=0,this.accel=0,this.originSide=this.options.rightToLeft?"right":"left",this.viewport=document.createElement("div"),this.viewport.className="flickity-viewport",p.setUnselectable(this.viewport),this._createSlider(),(this.options.resize||this.options.watchCSS)&&(e.bind(b,"resize",this),this.isResizeBound=!0);for(var c=0,d=p.createMethods.length;c<d;c++){var f=p.createMethods[c];this[f]()}this.options.watchCSS?this.watchCSS():this.activate()},p.prototype.option=function(a){g.extend(this.options,a)},p.prototype.activate=function(){if(!this.isActive){this.isActive=!0,c.add(this.element,"flickity-enabled"),this.options.rightToLeft&&c.add(this.element,"flickity-rtl"),this.getSize();var a=this._filterFindCellElements(this.element.children);m(a,this.slider),this.viewport.appendChild(this.slider),this.element.appendChild(this.viewport),this.reloadCells(),this.options.accessibility&&(this.element.tabIndex=0,e.bind(this.element,"keydown",this)),this.emit("activate");var b,d=this.options.initialIndex;b=this.isInitActivated?this.selectedIndex:void 0!==d&&this.cells[d]?d:0,this.select(b,!1,!0),this.isInitActivated=!0}},p.prototype._createSlider=function(){var a=document.createElement("div");a.className="flickity-slider",a.style[this.originSide]=0,this.slider=a},p.prototype._filterFindCellElements=function(a){return g.filterFindElements(a,this.options.cellSelector)},p.prototype.reloadCells=function(){this.cells=this._makeCells(this.slider.children),this.positionCells(),this._getWrapShiftCells(),this.setGallerySize()},p.prototype._makeCells=function(a){for(var b=this._filterFindCellElements(a),c=[],d=0,e=b.length;d<e;d++){var f=b[d],g=new h(f,this);c.push(g)}return c},p.prototype.getLastCell=function(){return this.cells[this.cells.length-1]},p.prototype.positionCells=function(){this._sizeCells(this.cells),this._positionCells(0)},p.prototype._positionCells=function(a){a=a||0,this.maxCellHeight=a?this.maxCellHeight||0:0;var b=0;if(a>0){var c=this.cells[a-1];b=c.x+c.size.outerWidth}for(var d,e=this.cells.length,f=a;f<e;f++)d=this.cells[f],d.setPosition(b),b+=d.size.outerWidth,this.maxCellHeight=Math.max(d.size.outerHeight,this.maxCellHeight);this.slideableWidth=b,this._containCells()},p.prototype._sizeCells=function(a){for(var b=0,c=a.length;b<c;b++){var d=a[b];d.getSize()}},p.prototype._init=p.prototype.reposition=function(){this.positionCells(),this.positionSliderAtSelected()},p.prototype.getSize=function(){this.size=f(this.element),this.setCellAlign(),this.cursorPosition=this.size.innerWidth*this.cellAlign};var q={center:{left:.5,right:.5},left:{left:0,right:1},right:{right:0,left:1}};p.prototype.setCellAlign=function(){var a=q[this.options.cellAlign];this.cellAlign=a?a[this.originSide]:this.options.cellAlign},p.prototype.setGallerySize=function(){this.options.setGallerySize&&(this.viewport.style.height=this.maxCellHeight+"px")},p.prototype._getWrapShiftCells=function(){if(this.options.wrapAround){this._unshiftCells(this.beforeShiftCells),this._unshiftCells(this.afterShiftCells);var a=this.cursorPosition,b=this.cells.length-1;this.beforeShiftCells=this._getGapCells(a,b,-1),a=this.size.innerWidth-this.cursorPosition,this.afterShiftCells=this._getGapCells(a,0,1)}},p.prototype._getGapCells=function(a,b,c){for(var d=[];a>0;){var e=this.cells[b];if(!e)break;d.push(e),b+=c,a-=e.size.outerWidth}return d},p.prototype._containCells=function(){if(this.options.contain&&!this.options.wrapAround&&this.cells.length)for(var a=this.options.rightToLeft?"marginRight":"marginLeft",b=this.options.rightToLeft?"marginLeft":"marginRight",c=this.cells[0].size[a],d=this.getLastCell(),e=this.slideableWidth-d.size[b],f=e-this.size.innerWidth*(1-this.cellAlign),g=e<this.size.innerWidth,h=0,i=this.cells.length;h<i;h++){var j=this.cells[h];j.setDefaultTarget(),g?j.target=e*this.cellAlign:(j.target=Math.max(j.target,this.cursorPosition+c),j.target=Math.min(j.target,f))}},p.prototype.dispatchEvent=function(a,b,c){var d=[b].concat(c);if(this.emitEvent(a,d),j&&this.$element)if(b){var e=j.Event(b);e.type=a,this.$element.trigger(e,c)}else this.$element.trigger(a,c)},p.prototype.select=function(a,b,c){if(this.isActive){a=parseInt(a,10);var d=this.cells.length;this.options.wrapAround&&d>1&&(a<0?this.x-=this.slideableWidth:a>=d&&(this.x+=this.slideableWidth)),(this.options.wrapAround||b)&&(a=g.modulo(a,d)),this.cells[a]&&(this.selectedIndex=a,this.setSelectedCell(),c?this.positionSliderAtSelected():this.startAnimation(),this.dispatchEvent("cellSelect"))}},p.prototype.previous=function(a){this.select(this.selectedIndex-1,a)},p.prototype.next=function(a){this.select(this.selectedIndex+1,a)},p.prototype.setSelectedCell=function(){this._removeSelectedCellClass(),this.selectedCell=this.cells[this.selectedIndex],this.selectedElement=this.selectedCell.element,c.add(this.selectedElement,"is-selected")},p.prototype._removeSelectedCellClass=function(){this.selectedCell&&c.remove(this.selectedCell.element,"is-selected")},p.prototype.getCell=function(a){for(var b=0,c=this.cells.length;b<c;b++){var d=this.cells[b];if(d.element==a)return d}},p.prototype.getCells=function(a){a=g.makeArray(a);for(var b=[],c=0,d=a.length;c<d;c++){var e=a[c],f=this.getCell(e);f&&b.push(f)}return b},p.prototype.getCellElements=function(){for(var a=[],b=0,c=this.cells.length;b<c;b++)a.push(this.cells[b].element);return a},p.prototype.getParentCell=function(a){var b=this.getCell(a);return b?b:(a=g.getParent(a,".flickity-slider > *"),this.getCell(a))},p.prototype.getAdjacentCellElements=function(a,b){if(!a)return[this.selectedElement];b=void 0===b?this.selectedIndex:b;var c=this.cells.length;if(1+2*a>=c)return this.getCellElements();for(var d=[],e=b-a;e<=b+a;e++){var f=this.options.wrapAround?g.modulo(e,c):e,h=this.cells[f];h&&d.push(h.element)}return d},p.prototype.uiChange=function(){this.emit("uiChange")},p.prototype.childUIPointerDown=function(a){this.emitEvent("childUIPointerDown",[a])},p.prototype.onresize=function(){this.watchCSS(),this.resize()},g.debounceMethod(p,"onresize",150),p.prototype.resize=function(){this.isActive&&(this.getSize(),this.options.wrapAround&&(this.x=g.modulo(this.x,this.slideableWidth)),this.positionCells(),this._getWrapShiftCells(),this.setGallerySize(),this.positionSliderAtSelected())};var r=p.supportsConditionalCSS=function(){var a;return function(){if(void 0!==a)return a;if(!k)return void(a=!1);var c=document.createElement("style"),d=document.createTextNode('body:after { content: "foo"; display: none; }');c.appendChild(d),document.head.appendChild(c);var e=k(document.body,":after").content;return a=e.indexOf("foo")!=-1,document.head.removeChild(c),a}}();p.prototype.watchCSS=function(){var a=this.options.watchCSS;if(a){var b=r();if(!b){var c="fallbackOn"==a?"activate":"deactivate";return void this[c]()}var d=k(this.element,":after").content;d.indexOf("flickity")!=-1?this.activate():this.deactivate()}},p.prototype.onkeydown=function(a){if(this.options.accessibility&&(!document.activeElement||document.activeElement==this.element))if(37==a.keyCode){var b=this.options.rightToLeft?"next":"previous";this.uiChange(),this[b]()}else if(39==a.keyCode){var c=this.options.rightToLeft?"previous":"next";this.uiChange(),this[c]()}},p.prototype.deactivate=function(){if(this.isActive){c.remove(this.element,"flickity-enabled"),c.remove(this.element,"flickity-rtl");for(var a=0,b=this.cells.length;a<b;a++){var d=this.cells[a];d.destroy()}this._removeSelectedCellClass(),this.element.removeChild(this.viewport),m(this.slider.children,this.element),this.options.accessibility&&(this.element.removeAttribute("tabIndex"),e.unbind(this.element,"keydown",this)),this.isActive=!1,this.emit("deactivate")}},p.prototype.destroy=function(){this.deactivate(),this.isResizeBound&&e.unbind(b,"resize",this),this.emit("destroy"),j&&this.$element&&j.removeData(this.element,"flickity"),delete this.element.flickityGUID,delete o[this.guid]},g.extend(p.prototype,i);var s="attachEvent"in b;return p.setUnselectable=function(a){s&&a.setAttribute("unselectable","on")},p.data=function(a){a=g.getQueryElement(a);var b=a&&a.flickityGUID;return b&&o[b]},g.htmlInit(p,"flickity"),j&&j.bridget&&j.bridget("flickity",p),p.Cell=h,p}),function(a,b){"use strict";"function"==typeof define&&define.amd?define("unipointer/unipointer",["eventEmitter/EventEmitter","eventie/eventie"],function(c,d){return b(a,c,d)}):"object"==typeof exports?module.exports=b(a,require("wolfy87-eventemitter"),require("eventie")):a.Unipointer=b(a,a.EventEmitter,a.eventie)}(window,function(b,c,d){function e(){}function f(){}f.prototype=new c,f.prototype.bindStartEvent=function(a){this._bindStartEvent(a,!0)},f.prototype.unbindStartEvent=function(a){this._bindStartEvent(a,!1)},f.prototype._bindStartEvent=function(a,c){c=void 0===c||!!c;var e=c?"bind":"unbind";b.navigator.pointerEnabled?d[e](a,"pointerdown",this):b.navigator.msPointerEnabled?d[e](a,"MSPointerDown",this):(d[e](a,"mousedown",this),d[e](a,"touchstart",this))},f.prototype.handleEvent=function(a){var b="on"+a.type;this[b]&&this[b](a)},f.prototype.getTouch=function(a){for(var b=0,c=a.length;b<c;b++){var d=a[b];if(d.identifier==this.pointerIdentifier)return d}},f.prototype.onmousedown=function(a){var b=a.button;b&&0!==b&&1!==b||this._pointerDown(a,a)},f.prototype.ontouchstart=function(a){this._pointerDown(a,a.changedTouches[0])},f.prototype.onMSPointerDown=f.prototype.onpointerdown=function(a){this._pointerDown(a,a)},f.prototype._pointerDown=function(a,b){this.isPointerDown||(this.isPointerDown=!0,this.pointerIdentifier=void 0!==b.pointerId?b.pointerId:b.identifier,this.pointerDown(a,b))},f.prototype.pointerDown=function(a,b){this._bindPostStartEvents(a),this.emitEvent("pointerDown",[a,b])};var g={mousedown:["mousemove","mouseup"],touchstart:["touchmove","touchend","touchcancel"],pointerdown:["pointermove","pointerup","pointercancel"],MSPointerDown:["MSPointerMove","MSPointerUp","MSPointerCancel"]};return f.prototype._bindPostStartEvents=function(a){if(a){for(var c=g[a.type],e=a.preventDefault?b:document,f=0,h=c.length;f<h;f++){var i=c[f];d.bind(e,i,this)}this._boundPointerEvents={events:c,node:e}}},f.prototype._unbindPostStartEvents=function(){var a=this._boundPointerEvents;if(a&&a.events){for(var b=0,c=a.events.length;b<c;b++){var e=a.events[b];d.unbind(a.node,e,this)}delete this._boundPointerEvents}},f.prototype.onmousemove=function(a){this._pointerMove(a,a)},f.prototype.onMSPointerMove=f.prototype.onpointermove=function(a){a.pointerId==this.pointerIdentifier&&this._pointerMove(a,a)},f.prototype.ontouchmove=function(a){var b=this.getTouch(a.changedTouches);b&&this._pointerMove(a,b)},f.prototype._pointerMove=function(a,b){this.pointerMove(a,b)},f.prototype.pointerMove=function(a,b){this.emitEvent("pointerMove",[a,b])},f.prototype.onmouseup=function(a){this._pointerUp(a,a)},f.prototype.onMSPointerUp=f.prototype.onpointerup=function(a){a.pointerId==this.pointerIdentifier&&this._pointerUp(a,a)},f.prototype.ontouchend=function(a){var b=this.getTouch(a.changedTouches);b&&this._pointerUp(a,b)},f.prototype._pointerUp=function(a,b){this._pointerDone(),this.pointerUp(a,b)},f.prototype.pointerUp=function(a,b){this.emitEvent("pointerUp",[a,b])},f.prototype._pointerDone=function(){this.isPointerDown=!1,delete this.pointerIdentifier,this._unbindPostStartEvents(),this.pointerDone()},f.prototype.pointerDone=e,f.prototype.onMSPointerCancel=f.prototype.onpointercancel=function(a){a.pointerId==this.pointerIdentifier&&this._pointerCancel(a,a)},f.prototype.ontouchcancel=function(a){var b=this.getTouch(a.changedTouches);b&&this._pointerCancel(a,b)},f.prototype._pointerCancel=function(a,b){this._pointerDone(),this.pointerCancel(a,b)},f.prototype.pointerCancel=function(a,b){this.emitEvent("pointerCancel",[a,b])},f.getPointerPoint=function(a){return{x:void 0!==a.pageX?a.pageX:a.clientX,y:void 0!==a.pageY?a.pageY:a.clientY}},f}),function(a,b){"use strict";"function"==typeof define&&define.amd?define("unidragger/unidragger",["eventie/eventie","unipointer/unipointer"],function(c,d){return b(a,c,d)}):"object"==typeof exports?module.exports=b(a,require("eventie"),require("unipointer")):a.Unidragger=b(a,a.eventie,a.Unipointer)}(window,function(b,c,d){function e(){}function f(a){a.preventDefault?a.preventDefault():a.returnValue=!1}function g(){}function i(){return!1}g.prototype=new d,g.prototype.bindHandles=function(){this._bindHandles(!0)},g.prototype.unbindHandles=function(){this._bindHandles(!1)};var h=b.navigator;g.prototype._bindHandles=function(a){a=void 0===a||!!a;var b;b=h.pointerEnabled?function(b){b.style.touchAction=a?"none":""}:h.msPointerEnabled?function(b){b.style.msTouchAction=a?"none":""}:function(){a&&k(g)};for(var d=a?"bind":"unbind",e=0,f=this.handles.length;e<f;e++){var g=this.handles[e];this._bindStartEvent(g,a),b(g),c[d](g,"click",this)}};var j="attachEvent"in document.documentElement,k=j?function(a){"IMG"==a.nodeName&&(a.ondragstart=i);for(var b=a.querySelectorAll("img"),c=0,d=b.length;c<d;c++){var e=b[c];e.ondragstart=i}}:e;g.prototype.pointerDown=function(a,d){if("INPUT"==a.target.nodeName&&"range"==a.target.type)return this.isPointerDown=!1,void delete this.pointerIdentifier;this._dragPointerDown(a,d);var e=document.activeElement;e&&e.blur&&e.blur(),this._bindPostStartEvents(a),this.pointerDownScroll=g.getScrollPosition(),c.bind(b,"scroll",this),this.emitEvent("pointerDown",[a,d])},g.prototype._dragPointerDown=function(a,b){this.pointerDownPoint=d.getPointerPoint(b);var c="touchstart"==a.type,e=a.target.nodeName;c||"SELECT"==e||f(a)},g.prototype.pointerMove=function(a,b){var c=this._dragPointerMove(a,b);this.emitEvent("pointerMove",[a,b,c]),this._dragMove(a,b,c)},g.prototype._dragPointerMove=function(a,b){var c=d.getPointerPoint(b),e={x:c.x-this.pointerDownPoint.x,y:c.y-this.pointerDownPoint.y};return!this.isDragging&&this.hasDragStarted(e)&&this._dragStart(a,b),e},g.prototype.hasDragStarted=function(a){return Math.abs(a.x)>3||Math.abs(a.y)>3},g.prototype.pointerUp=function(a,b){this.emitEvent("pointerUp",[a,b]),this._dragPointerUp(a,b)},g.prototype._dragPointerUp=function(a,b){this.isDragging?this._dragEnd(a,b):this._staticClick(a,b)},g.prototype.pointerDone=function(){c.unbind(b,"scroll",this)},g.prototype._dragStart=function(a,b){
    this.isDragging=!0,this.dragStartPoint=g.getPointerPoint(b),this.isPreventingClicks=!0,this.dragStart(a,b)},g.prototype.dragStart=function(a,b){this.emitEvent("dragStart",[a,b])},g.prototype._dragMove=function(a,b,c){this.isDragging&&this.dragMove(a,b,c)},g.prototype.dragMove=function(a,b,c){f(a),this.emitEvent("dragMove",[a,b,c])},g.prototype._dragEnd=function(a,b){this.isDragging=!1;var c=this;setTimeout(function(){delete c.isPreventingClicks}),this.dragEnd(a,b)},g.prototype.dragEnd=function(a,b){this.emitEvent("dragEnd",[a,b])},g.prototype.pointerDone=function(){c.unbind(b,"scroll",this),delete this.pointerDownScroll},g.prototype.onclick=function(a){this.isPreventingClicks&&f(a)},g.prototype._staticClick=function(a,b){if(!this.isIgnoringMouseUp||"mouseup"!=a.type){var c=a.target.nodeName;if("INPUT"!=c&&"TEXTAREA"!=c||a.target.focus(),this.staticClick(a,b),"mouseup"!=a.type){this.isIgnoringMouseUp=!0;var d=this;setTimeout(function(){delete d.isIgnoringMouseUp},400)}}},g.prototype.staticClick=function(a,b){this.emitEvent("staticClick",[a,b])},g.prototype.onscroll=function(){var a=g.getScrollPosition(),b=this.pointerDownScroll.x-a.x,c=this.pointerDownScroll.y-a.y;(Math.abs(b)>3||Math.abs(c)>3)&&this._pointerDone()},g.getPointerPoint=function(a){return{x:void 0!==a.pageX?a.pageX:a.clientX,y:void 0!==a.pageY?a.pageY:a.clientY}};var l=void 0!==b.pageYOffset;return g.getScrollPosition=function(){return{x:l?b.pageXOffset:document.body.scrollLeft,y:l?b.pageYOffset:document.body.scrollTop}},g.getPointerPoint=d.getPointerPoint,g}),function(a,b){"use strict";"function"==typeof define&&define.amd?define("flickity/js/drag",["classie/classie","eventie/eventie","./flickity","unidragger/unidragger","fizzy-ui-utils/utils"],function(c,d,e,f,g){return b(a,c,d,e,f,g)}):"object"==typeof exports?module.exports=b(a,require("desandro-classie"),require("eventie"),require("./flickity"),require("unidragger"),require("fizzy-ui-utils")):a.Flickity=b(a,a.classie,a.eventie,a.Flickity,a.Unidragger,a.fizzyUIUtils)}(window,function(b,c,d,e,f,g){function h(a){a.preventDefault?a.preventDefault():a.returnValue=!1}g.extend(e.defaults,{draggable:!0}),e.createMethods.push("_createDrag"),g.extend(e.prototype,f.prototype),e.prototype._createDrag=function(){this.on("activate",this.bindDrag),this.on("uiChange",this._uiChangeDrag),this.on("childUIPointerDown",this._childUIPointerDownDrag),this.on("deactivate",this.unbindDrag)},e.prototype.bindDrag=function(){this.options.draggable&&!this.isDragBound&&(c.add(this.element,"is-draggable"),this.handles=[this.viewport],this.bindHandles(),this.isDragBound=!0)},e.prototype.unbindDrag=function(){this.isDragBound&&(c.remove(this.element,"is-draggable"),this.unbindHandles(),delete this.isDragBound)},e.prototype._uiChangeDrag=function(){delete this.isFreeScrolling},e.prototype._childUIPointerDownDrag=function(a){h(a),this.pointerDownFocus(a)},e.prototype.pointerDown=function(a,e){if("INPUT"==a.target.nodeName&&"range"==a.target.type)return this.isPointerDown=!1,void delete this.pointerIdentifier;this._dragPointerDown(a,e);var g=document.activeElement;g&&g.blur&&g!=this.element&&g!=document.body&&g.blur(),this.pointerDownFocus(a),this.dragX=this.x,c.add(this.viewport,"is-pointer-down"),this._bindPostStartEvents(a),this.pointerDownScroll=f.getScrollPosition(),d.bind(b,"scroll",this),this.dispatchEvent("pointerDown",a,[e])};var i={touchstart:!0,MSPointerDown:!0},j={INPUT:!0,SELECT:!0};return e.prototype.pointerDownFocus=function(a){if(this.options.accessibility&&!i[a.type]&&!j[a.target.nodeName]){var c=b.pageYOffset;this.element.focus(),b.pageYOffset!=c&&b.scrollTo(b.pageXOffset,c)}},e.prototype.hasDragStarted=function(a){return Math.abs(a.x)>3},e.prototype.pointerUp=function(a,b){c.remove(this.viewport,"is-pointer-down"),this.dispatchEvent("pointerUp",a,[b]),this._dragPointerUp(a,b)},e.prototype.pointerDone=function(){d.unbind(b,"scroll",this),delete this.pointerDownScroll},e.prototype.dragStart=function(a,b){this.dragStartPosition=this.x,this.startAnimation(),this.dispatchEvent("dragStart",a,[b])},e.prototype.dragMove=function(a,b,c){h(a),this.previousDragX=this.dragX;var d=this.options.rightToLeft?-1:1,e=this.dragStartPosition+c.x*d;if(!this.options.wrapAround&&this.cells.length){var f=Math.max(-this.cells[0].target,this.dragStartPosition);e=e>f?.5*(e+f):e;var g=Math.min(-this.getLastCell().target,this.dragStartPosition);e=e<g?.5*(e+g):e}this.dragX=e,this.dragMoveTime=new Date,this.dispatchEvent("dragMove",a,[b,c])},e.prototype.dragEnd=function(a,b){this.options.freeScroll&&(this.isFreeScrolling=!0);var c=this.dragEndRestingSelect();if(this.options.freeScroll&&!this.options.wrapAround){var d=this.getRestingPosition();this.isFreeScrolling=-d>this.cells[0].target&&-d<this.getLastCell().target}else this.options.freeScroll||c!=this.selectedIndex||(c+=this.dragEndBoostSelect());delete this.previousDragX,this.select(c),this.dispatchEvent("dragEnd",a,[b])},e.prototype.dragEndRestingSelect=function(){var a=this.getRestingPosition(),b=Math.abs(this.getCellDistance(-a,this.selectedIndex)),c=this._getClosestResting(a,b,1),d=this._getClosestResting(a,b,-1),e=c.distance<d.distance?c.index:d.index;return e},e.prototype._getClosestResting=function(a,b,c){for(var d=this.selectedIndex,e=1/0,f=this.options.contain&&!this.options.wrapAround?function(a,b){return a<=b}:function(a,b){return a<b};f(b,e)&&(d+=c,e=b,b=this.getCellDistance(-a,d),null!==b);)b=Math.abs(b);return{distance:e,index:d-c}},e.prototype.getCellDistance=function(a,b){var c=this.cells.length,d=this.options.wrapAround&&c>1,e=d?g.modulo(b,c):b,f=this.cells[e];if(!f)return null;var h=d?this.slideableWidth*Math.floor(b/c):0;return a-(f.target+h)},e.prototype.dragEndBoostSelect=function(){if(void 0===this.previousDragX||!this.dragMoveTime||new Date-this.dragMoveTime>100)return 0;var a=this.getCellDistance(-this.dragX,this.selectedIndex),b=this.previousDragX-this.dragX;return a>0&&b>0?1:a<0&&b<0?-1:0},e.prototype.staticClick=function(a,b){var c=this.getParentCell(a.target),d=c&&c.element,e=c&&g.indexOf(this.cells,c);this.dispatchEvent("staticClick",a,[b,d,e])},e}),function(a,b){"function"==typeof define&&define.amd?define("tap-listener/tap-listener",["unipointer/unipointer"],function(c){return b(a,c)}):"object"==typeof exports?module.exports=b(a,require("unipointer")):a.TapListener=b(a,a.Unipointer)}(window,function(b,c){function d(a){this.bindTap(a)}d.prototype=new c,d.prototype.bindTap=function(a){a&&(this.unbindTap(),this.tapElement=a,this._bindStartEvent(a,!0))},d.prototype.unbindTap=function(){this.tapElement&&(this._bindStartEvent(this.tapElement,!0),delete this.tapElement)};var e=void 0!==b.pageYOffset;return d.prototype.pointerUp=function(a,d){if(!this.isIgnoringMouseUp||"mouseup"!=a.type){var f=c.getPointerPoint(d),g=this.tapElement.getBoundingClientRect(),h=e?b.pageXOffset:document.body.scrollLeft,i=e?b.pageYOffset:document.body.scrollTop,j=f.x>=g.left+h&&f.x<=g.right+h&&f.y>=g.top+i&&f.y<=g.bottom+i;j&&this.emitEvent("tap",[a,d]),"mouseup"!=a.type&&(this.isIgnoringMouseUp=!0,setTimeout(function(){delete this.isIgnoringMouseUp}.bind(this),320))}},d.prototype.destroy=function(){this.pointerDone(),this.unbindTap()},d}),function(a,b){"use strict";"function"==typeof define&&define.amd?define("flickity/js/prev-next-button",["eventie/eventie","./flickity","tap-listener/tap-listener","fizzy-ui-utils/utils"],function(c,d,e,f){return b(a,c,d,e,f)}):"object"==typeof exports?module.exports=b(a,require("eventie"),require("./flickity"),require("tap-listener"),require("fizzy-ui-utils")):b(a,a.eventie,a.Flickity,a.TapListener,a.fizzyUIUtils)}(window,function(b,c,d,e,f){function i(a,b){this.direction=a,this.parent=b,this._create()}function j(a){return"string"==typeof a?a:"M "+a.x0+",50 L "+a.x1+","+(a.y1+50)+" L "+a.x2+","+(a.y2+50)+" L "+a.x3+",50  L "+a.x2+","+(50-a.y2)+" L "+a.x1+","+(50-a.y1)+" Z"}var g="http://www.w3.org/2000/svg",h=function(){function b(){if(void 0!==a)return a;var b=document.createElement("div");return b.innerHTML="<svg/>",a=(b.firstChild&&b.firstChild.namespaceURI)==g}var a;return b}();return i.prototype=new e,i.prototype._create=function(){this.isEnabled=!0,this.isPrevious=this.direction==-1;var a=this.parent.options.rightToLeft?1:-1;this.isLeft=this.direction==a;var b=this.element=document.createElement("button");if(b.className="flickity-prev-next-button",b.className+=this.isPrevious?" previous":" next",b.setAttribute("type","button"),this.disable(),b.setAttribute("aria-label",this.isPrevious?"previous":"next"),d.setUnselectable(b),h()){var c=this.createSVG();b.appendChild(c)}else this.setArrowText(),b.className+=" no-svg";var e=this;this.onCellSelect=function(){e.update()},this.parent.on("cellSelect",this.onCellSelect),this.on("tap",this.onTap),this.on("pointerDown",function(b,c){e.parent.childUIPointerDown(c)})},i.prototype.activate=function(){this.bindTap(this.element),c.bind(this.element,"click",this),this.parent.element.appendChild(this.element)},i.prototype.deactivate=function(){this.parent.element.removeChild(this.element),e.prototype.destroy.call(this),c.unbind(this.element,"click",this)},i.prototype.createSVG=function(){var a=document.createElementNS(g,"svg");a.setAttribute("viewBox","0 0 100 100");var b=document.createElementNS(g,"path"),c=j(this.parent.options.arrowShape);return b.setAttribute("d",c),b.setAttribute("class","arrow"),this.isLeft||b.setAttribute("transform","translate(100, 100) rotate(180) "),a.appendChild(b),a},i.prototype.setArrowText=function(){var a=this.parent.options,b=this.isLeft?a.leftArrowText:a.rightArrowText;f.setText(this.element,b)},i.prototype.onTap=function(){if(this.isEnabled){this.parent.uiChange();var a=this.isPrevious?"previous":"next";this.parent[a]()}},i.prototype.handleEvent=f.handleEvent,i.prototype.onclick=function(){var a=document.activeElement;a&&a==this.element&&this.onTap()},i.prototype.enable=function(){this.isEnabled||(this.element.disabled=!1,this.isEnabled=!0)},i.prototype.disable=function(){this.isEnabled&&(this.element.disabled=!0,this.isEnabled=!1)},i.prototype.update=function(){var a=this.parent.cells;if(this.parent.options.wrapAround&&a.length>1)return void this.enable();var b=a.length?a.length-1:0,c=this.isPrevious?0:b,d=this.parent.selectedIndex==c?"disable":"enable";this[d]()},i.prototype.destroy=function(){this.deactivate()},f.extend(d.defaults,{prevNextButtons:!0,leftArrowText:"‹",rightArrowText:"›",arrowShape:{x0:10,x1:60,y1:50,x2:70,y2:40,x3:30}}),d.createMethods.push("_createPrevNextButtons"),d.prototype._createPrevNextButtons=function(){this.options.prevNextButtons&&(this.prevButton=new i(-1,this),this.nextButton=new i(1,this),this.on("activate",this.activatePrevNextButtons))},d.prototype.activatePrevNextButtons=function(){this.prevButton.activate(),this.nextButton.activate(),this.on("deactivate",this.deactivatePrevNextButtons)},d.prototype.deactivatePrevNextButtons=function(){this.prevButton.deactivate(),this.nextButton.deactivate(),this.off("deactivate",this.deactivatePrevNextButtons)},d.PrevNextButton=i,d}),function(a,b){"use strict";"function"==typeof define&&define.amd?define("flickity/js/page-dots",["eventie/eventie","./flickity","tap-listener/tap-listener","fizzy-ui-utils/utils"],function(c,d,e,f){return b(a,c,d,e,f)}):"object"==typeof exports?module.exports=b(a,require("eventie"),require("./flickity"),require("tap-listener"),require("fizzy-ui-utils")):b(a,a.eventie,a.Flickity,a.TapListener,a.fizzyUIUtils)}(window,function(b,c,d,e,f){function g(a){this.parent=a,this._create()}return g.prototype=new e,g.prototype._create=function(){this.holder=document.createElement("ol"),this.holder.className="flickity-page-dots",d.setUnselectable(this.holder),this.dots=[];var a=this;this.onCellSelect=function(){a.updateSelected()},this.parent.on("cellSelect",this.onCellSelect),this.on("tap",this.onTap),this.on("pointerDown",function(c,d){a.parent.childUIPointerDown(d)})},g.prototype.activate=function(){this.setDots(),this.bindTap(this.holder),this.parent.element.appendChild(this.holder)},g.prototype.deactivate=function(){this.parent.element.removeChild(this.holder),e.prototype.destroy.call(this)},g.prototype.setDots=function(){var a=this.parent.cells.length-this.dots.length;a>0?this.addDots(a):a<0&&this.removeDots(-a)},g.prototype.addDots=function(a){for(var b=document.createDocumentFragment(),c=[];a;){var d=document.createElement("li");d.className="dot",b.appendChild(d),c.push(d),a--}this.holder.appendChild(b),this.dots=this.dots.concat(c)},g.prototype.removeDots=function(a){for(var b=this.dots.splice(this.dots.length-a,a),c=0,d=b.length;c<d;c++){var e=b[c];this.holder.removeChild(e)}},g.prototype.updateSelected=function(){this.selectedDot&&(this.selectedDot.className="dot"),this.dots.length&&(this.selectedDot=this.dots[this.parent.selectedIndex],this.selectedDot.className="dot is-selected")},g.prototype.onTap=function(a){var b=a.target;if("LI"==b.nodeName){this.parent.uiChange();var c=f.indexOf(this.dots,b);this.parent.select(c)}},g.prototype.destroy=function(){this.deactivate()},d.PageDots=g,f.extend(d.defaults,{pageDots:!0}),d.createMethods.push("_createPageDots"),d.prototype._createPageDots=function(){this.options.pageDots&&(this.pageDots=new g(this),this.on("activate",this.activatePageDots),this.on("cellAddedRemoved",this.onCellAddedRemovedPageDots),this.on("deactivate",this.deactivatePageDots))},d.prototype.activatePageDots=function(){this.pageDots.activate()},d.prototype.onCellAddedRemovedPageDots=function(){this.pageDots.setDots()},d.prototype.deactivatePageDots=function(){this.pageDots.deactivate()},d.PageDots=g,d}),function(a,b){"use strict";"function"==typeof define&&define.amd?define("flickity/js/player",["eventEmitter/EventEmitter","eventie/eventie","fizzy-ui-utils/utils","./flickity"],function(a,c,d,e){return b(a,c,d,e)}):"object"==typeof exports?module.exports=b(require("wolfy87-eventemitter"),require("eventie"),require("fizzy-ui-utils"),require("./flickity")):b(a.EventEmitter,a.eventie,a.fizzyUIUtils,a.Flickity)}(window,function(b,c,d,e){function h(a){if(this.parent=a,this.state="stopped",g){var b=this;this.onVisibilityChange=function(){b.visibilityChange()}}}var f,g;return"hidden"in document?(f="hidden",g="visibilitychange"):"webkitHidden"in document&&(f="webkitHidden",g="webkitvisibilitychange"),h.prototype=new b,h.prototype.play=function(){"playing"!=this.state&&(this.state="playing",g&&document.addEventListener(g,this.onVisibilityChange,!1),this.tick())},h.prototype.tick=function(){if("playing"==this.state){var a=this.parent.options.autoPlay;a="number"==typeof a?a:3e3;var b=this;this.clear(),this.timeout=setTimeout(function(){b.parent.next(!0),b.tick()},a)}},h.prototype.stop=function(){this.state="stopped",this.clear(),g&&document.removeEventListener(g,this.onVisibilityChange,!1)},h.prototype.clear=function(){clearTimeout(this.timeout)},h.prototype.pause=function(){"playing"==this.state&&(this.state="paused",this.clear())},h.prototype.unpause=function(){"paused"==this.state&&this.play()},h.prototype.visibilityChange=function(){var a=document[f];this[a?"pause":"unpause"]()},d.extend(e.defaults,{pauseAutoPlayOnHover:!0}),e.createMethods.push("_createPlayer"),e.prototype._createPlayer=function(){this.player=new h(this),this.on("activate",this.activatePlayer),this.on("uiChange",this.stopPlayer),this.on("pointerDown",this.stopPlayer),this.on("deactivate",this.deactivatePlayer)},e.prototype.activatePlayer=function(){this.options.autoPlay&&(this.player.play(),c.bind(this.element,"mouseenter",this),this.isMouseenterBound=!0)},e.prototype.playPlayer=function(){this.player.play()},e.prototype.stopPlayer=function(){this.player.stop()},e.prototype.pausePlayer=function(){this.player.pause()},e.prototype.unpausePlayer=function(){this.player.unpause()},e.prototype.deactivatePlayer=function(){this.player.stop(),this.isMouseenterBound&&(c.unbind(this.element,"mouseenter",this),delete this.isMouseenterBound)},e.prototype.onmouseenter=function(){this.options.pauseAutoPlayOnHover&&(this.player.pause(),c.bind(this.element,"mouseleave",this))},e.prototype.onmouseleave=function(){this.player.unpause(),c.unbind(this.element,"mouseleave",this)},e.Player=h,e}),function(a,b){"use strict";"function"==typeof define&&define.amd?define("flickity/js/add-remove-cell",["./flickity","fizzy-ui-utils/utils"],function(c,d){return b(a,c,d)}):"object"==typeof exports?module.exports=b(a,require("./flickity"),require("fizzy-ui-utils")):b(a,a.Flickity,a.fizzyUIUtils)}(window,function(b,c,d){function e(a){for(var b=document.createDocumentFragment(),c=0,d=a.length;c<d;c++){var e=a[c];b.appendChild(e.element)}return b}return c.prototype.insert=function(a,b){var c=this._makeCells(a);if(c&&c.length){var d=this.cells.length;b=void 0===b?d:b;var f=e(c),g=b==d;if(g)this.slider.appendChild(f);else{var h=this.cells[b].element;this.slider.insertBefore(f,h)}if(0===b)this.cells=c.concat(this.cells);else if(g)this.cells=this.cells.concat(c);else{var i=this.cells.splice(b,d-b);this.cells=this.cells.concat(c).concat(i)}this._sizeCells(c);var j=b>this.selectedIndex?0:c.length;this._cellAddedRemoved(b,j)}},c.prototype.append=function(a){this.insert(a,this.cells.length)},c.prototype.prepend=function(a){this.insert(a,0)},c.prototype.remove=function(a){var e,f,g,b=this.getCells(a),c=0;for(e=0,f=b.length;e<f;e++){g=b[e];var h=d.indexOf(this.cells,g)<this.selectedIndex;c-=h?1:0}for(e=0,f=b.length;e<f;e++)g=b[e],g.remove(),d.removeFrom(this.cells,g);b.length&&this._cellAddedRemoved(0,c)},c.prototype._cellAddedRemoved=function(a,b){b=b||0,this.selectedIndex+=b,this.selectedIndex=Math.max(0,Math.min(this.cells.length-1,this.selectedIndex)),this.emitEvent("cellAddedRemoved",[a,b]),this.cellChange(a,!0)},c.prototype.cellSizeChange=function(a){var b=this.getCell(a);if(b){b.getSize();var c=d.indexOf(this.cells,b);this.cellChange(c)}},c.prototype.cellChange=function(a,b){var c=this.slideableWidth;if(this._positionCells(a),this._getWrapShiftCells(),this.setGallerySize(),this.options.freeScroll){var d=c-this.slideableWidth;this.x+=d*this.cellAlign,this.positionSlider()}else b&&this.positionSliderAtSelected(),this.select(this.selectedIndex)},c}),function(a,b){"use strict";"function"==typeof define&&define.amd?define("flickity/js/lazyload",["classie/classie","eventie/eventie","./flickity","fizzy-ui-utils/utils"],function(c,d,e,f){return b(a,c,d,e,f)}):"object"==typeof exports?module.exports=b(a,require("desandro-classie"),require("eventie"),require("./flickity"),require("fizzy-ui-utils")):b(a,a.classie,a.eventie,a.Flickity,a.fizzyUIUtils)}(window,function(b,c,d,e,f){"use strict";function g(a){if("IMG"==a.nodeName&&a.getAttribute("data-flickity-lazyload"))return[a];var b=a.querySelectorAll("img[data-flickity-lazyload]");return f.makeArray(b)}function h(a,b){this.img=a,this.flickity=b,this.load()}return e.createMethods.push("_createLazyload"),e.prototype._createLazyload=function(){this.on("cellSelect",this.lazyLoad)},e.prototype.lazyLoad=function(){var a=this.options.lazyLoad;if(a){for(var b="number"==typeof a?a:0,c=this.getAdjacentCellElements(b),d=[],e=0,f=c.length;e<f;e++){var i=c[e],j=g(i);d=d.concat(j)}for(e=0,f=d.length;e<f;e++){var k=d[e];new h(k,this)}}},h.prototype.handleEvent=f.handleEvent,h.prototype.load=function(){d.bind(this.img,"load",this),d.bind(this.img,"error",this),this.img.src=this.img.getAttribute("data-flickity-lazyload"),this.img.removeAttribute("data-flickity-lazyload")},h.prototype.onload=function(a){this.complete(a,"flickity-lazyloaded")},h.prototype.onerror=function(a){this.complete(a,"flickity-lazyerror")},h.prototype.complete=function(a,b){d.unbind(this.img,"load",this),d.unbind(this.img,"error",this);var e=this.flickity.getParentCell(this.img),f=e&&e.element;this.flickity.cellSizeChange(f),c.add(this.img,b),this.flickity.dispatchEvent("lazyLoad",a,f)},e.LazyLoader=h,e}),function(a,b){"use strict";"function"==typeof define&&define.amd?define("flickity/js/index",["./flickity","./drag","./prev-next-button","./page-dots","./player","./add-remove-cell","./lazyload"],b):"object"==typeof exports&&(module.exports=b(require("./flickity"),require("./drag"),require("./prev-next-button"),require("./page-dots"),require("./player"),require("./add-remove-cell"),require("./lazyload")))}(window,function(b){return b}),function(a,b){"use strict";"function"==typeof define&&define.amd?define("flickity-as-nav-for/as-nav-for",["classie/classie","flickity/js/index","fizzy-ui-utils/utils"],function(c,d,e){return b(a,c,d,e)}):"object"==typeof exports?module.exports=b(a,require("desandro-classie"),require("flickity"),require("fizzy-ui-utils")):a.Flickity=b(a,a.classie,a.Flickity,a.fizzyUIUtils)}(window,function(b,c,d,e){return d.createMethods.push("_createAsNavFor"),d.prototype._createAsNavFor=function(){this.on("activate",this.activateAsNavFor),this.on("deactivate",this.deactivateAsNavFor),this.on("destroy",this.destroyAsNavFor);var a=this.options.asNavFor;if(a){var b=this;setTimeout(function(){b.setNavCompanion(a)})}},d.prototype.setNavCompanion=function(a){a=e.getQueryElement(a);var b=d.data(a);if(b&&b!=this){this.navCompanion=b;var c=this;this.onNavCompanionSelect=function(){c.navCompanionSelect()},b.on("cellSelect",this.onNavCompanionSelect),this.on("staticClick",this.onNavStaticClick),this.navCompanionSelect()}},d.prototype.navCompanionSelect=function(){if(this.navCompanion){var a=this.navCompanion.selectedIndex;this.select(a),this.removeNavSelectedElement(),this.selectedIndex==a&&(this.navSelectedElement=this.cells[a].element,c.add(this.navSelectedElement,"is-nav-selected"))}},d.prototype.activateAsNavFor=function(){this.navCompanionSelect()},d.prototype.removeNavSelectedElement=function(){this.navSelectedElement&&(c.remove(this.navSelectedElement,"is-nav-selected"),delete this.navSelectedElement)},d.prototype.onNavStaticClick=function(a,b,c,d){"number"==typeof d&&this.navCompanion.select(d)},d.prototype.deactivateAsNavFor=function(){this.removeNavSelectedElement()},d.prototype.destroyAsNavFor=function(){this.navCompanion&&(this.navCompanion.off("cellSelect",this.onNavCompanionSelect),this.off("staticClick",this.onNavStaticClick),delete this.navCompanion)},d}),function(a,b){"use strict";"function"==typeof define&&define.amd?define("imagesloaded/imagesloaded",["eventEmitter/EventEmitter","eventie/eventie"],function(c,d){return b(a,c,d)}):"object"==typeof module&&module.exports?module.exports=b(a,require("wolfy87-eventemitter"),require("eventie")):a.imagesLoaded=b(a,a.EventEmitter,a.eventie)}(window,function(b,c,d){function g(a,b){for(var c in b)a[c]=b[c];return a}function i(a){return"[object Array]"==h.call(a)}function j(a){var b=[];if(i(a))b=a;else if("number"==typeof a.length)for(var c=0;c<a.length;c++)b.push(a[c]);else b.push(a);return b}function k(a,b,c){if(!(this instanceof k))return new k(a,b,c);"string"==typeof a&&(a=document.querySelectorAll(a)),this.elements=j(a),this.options=g({},this.options),"function"==typeof b?c=b:g(this.options,b),c&&this.on("always",c),this.getImages(),e&&(this.jqDeferred=new e.Deferred);var d=this;setTimeout(function(){d.check()})}function n(a){this.img=a}function o(a,b){this.url=a,this.element=b,this.img=new Image}var e=b.jQuery,f=b.console,h=Object.prototype.toString;k.prototype=new c,k.prototype.options={},k.prototype.getImages=function(){this.images=[];for(var a=0;a<this.elements.length;a++){var b=this.elements[a];this.addElementImages(b)}},k.prototype.addElementImages=function(a){"IMG"==a.nodeName&&this.addImage(a),this.options.background===!0&&this.addElementBackgroundImages(a);var b=a.nodeType;if(b&&l[b]){for(var c=a.querySelectorAll("img"),d=0;d<c.length;d++){var e=c[d];this.addImage(e)}if("string"==typeof this.options.background){var f=a.querySelectorAll(this.options.background);for(d=0;d<f.length;d++){var g=f[d];this.addElementBackgroundImages(g)}}}};var l={1:!0,9:!0,11:!0};k.prototype.addElementBackgroundImages=function(a){for(var b=m(a),c=/url\(['"]*([^'"\)]+)['"]*\)/gi,d=c.exec(b.backgroundImage);null!==d;){var e=d&&d[1];e&&this.addBackground(e,a),d=c.exec(b.backgroundImage)}};var m=b.getComputedStyle||function(a){return a.currentStyle};return k.prototype.addImage=function(a){var b=new n(a);this.images.push(b)},k.prototype.addBackground=function(a,b){var c=new o(a,b);this.images.push(c)},k.prototype.check=function(){function b(b,c,d){setTimeout(function(){a.progress(b,c,d)})}var a=this;if(this.progressedCount=0,this.hasAnyBroken=!1,!this.images.length)return void this.complete();for(var c=0;c<this.images.length;c++){var d=this.images[c];d.once("progress",b),d.check()}},k.prototype.progress=function(a,b,c){this.progressedCount++,this.hasAnyBroken=this.hasAnyBroken||!a.isLoaded,this.emit("progress",this,a,b),this.jqDeferred&&this.jqDeferred.notify&&this.jqDeferred.notify(this,a),this.progressedCount==this.images.length&&this.complete(),this.options.debug&&f&&f.log("progress: "+c,a,b)},k.prototype.complete=function(){var a=this.hasAnyBroken?"fail":"done";if(this.isComplete=!0,this.emit(a,this),this.emit("always",this),this.jqDeferred){var b=this.hasAnyBroken?"reject":"resolve";this.jqDeferred[b](this)}},n.prototype=new c,n.prototype.check=function(){var a=this.getIsImageComplete();return a?void this.confirm(0!==this.img.naturalWidth,"naturalWidth"):(this.proxyImage=new Image,d.bind(this.proxyImage,"load",this),d.bind(this.proxyImage,"error",this),d.bind(this.img,"load",this),d.bind(this.img,"error",this),void(this.proxyImage.src=this.img.src))},n.prototype.getIsImageComplete=function(){return this.img.complete&&void 0!==this.img.naturalWidth},n.prototype.confirm=function(a,b){this.isLoaded=a,this.emit("progress",this,this.img,b)},n.prototype.handleEvent=function(a){var b="on"+a.type;this[b]&&this[b](a)},n.prototype.onload=function(){this.confirm(!0,"onload"),this.unbindEvents()},n.prototype.onerror=function(){this.confirm(!1,"onerror"),this.unbindEvents()},n.prototype.unbindEvents=function(){d.unbind(this.proxyImage,"load",this),d.unbind(this.proxyImage,"error",this),d.unbind(this.img,"load",this),d.unbind(this.img,"error",this)},o.prototype=new n,o.prototype.check=function(){d.bind(this.img,"load",this),d.bind(this.img,"error",this),this.img.src=this.url;var a=this.getIsImageComplete();a&&(this.confirm(0!==this.img.naturalWidth,"naturalWidth"),this.unbindEvents())},o.prototype.unbindEvents=function(){d.unbind(this.img,"load",this),d.unbind(this.img,"error",this)},o.prototype.confirm=function(a,b){this.isLoaded=a,this.emit("progress",this,this.element,b)},k.makeJQueryPlugin=function(a){a=a||b.jQuery,a&&(e=a,e.fn.imagesLoaded=function(a,b){var c=new k(this,a,b);return c.jqDeferred.promise(e(this))})},k.makeJQueryPlugin(),k}),function(a,b){"use strict";"function"==typeof define&&define.amd?define(["flickity/js/index","imagesloaded/imagesloaded"],function(c,d){return b(a,c,d)}):"object"==typeof exports?module.exports=b(a,require("flickity"),require("imagesloaded")):a.Flickity=b(a,a.Flickity,a.imagesLoaded)}(window,function(b,c,d){"use strict";return c.createMethods.push("_createImagesLoaded"),c.prototype._createImagesLoaded=function(){this.on("activate",this.imagesLoaded)},c.prototype.imagesLoaded=function(){function b(b,c){var d=a.getParentCell(c.img);a.cellSizeChange(d&&d.element),a.options.freeScroll||a.positionSliderAtSelected()}if(this.options.imagesLoaded){var a=this;d(this.slider).on("progress",b)}},c});;
/*!
 * Isotope PACKAGED v3.0.1
 *
 * Licensed GPLv3 for open source use
 * or Isotope Commercial License for commercial use
 *
 * http://isotope.metafizzy.co
 * Copyright 2016 Metafizzy
 */

!function(t,e){"use strict";"function"==typeof define&&define.amd?define("jquery-bridget/jquery-bridget",["jquery"],function(i){e(t,i)}):"object"==typeof module&&module.exports?module.exports=e(t,require("jquery")):t.jQueryBridget=e(t,t.jQuery)}(window,function(t,e){"use strict";function i(i,s,a){function u(t,e,n){var o,s="$()."+i+'("'+e+'")';return t.each(function(t,u){var h=a.data(u,i);if(!h)return void r(i+" not initialized. Cannot call methods, i.e. "+s);var d=h[e];if(!d||"_"==e.charAt(0))return void r(s+" is not a valid method");var l=d.apply(h,n);o=void 0===o?l:o}),void 0!==o?o:t}function h(t,e){t.each(function(t,n){var o=a.data(n,i);o?(o.option(e),o._init()):(o=new s(n,e),a.data(n,i,o))})}a=a||e||t.jQuery,a&&(s.prototype.option||(s.prototype.option=function(t){a.isPlainObject(t)&&(this.options=a.extend(!0,this.options,t))}),a.fn[i]=function(t){if("string"==typeof t){var e=o.call(arguments,1);return u(this,t,e)}return h(this,t),this},n(a))}function n(t){!t||t&&t.bridget||(t.bridget=i)}var o=Array.prototype.slice,s=t.console,r="undefined"==typeof s?function(){}:function(t){s.error(t)};return n(e||t.jQuery),i}),function(t,e){"function"==typeof define&&define.amd?define("ev-emitter/ev-emitter",e):"object"==typeof module&&module.exports?module.exports=e():t.EvEmitter=e()}("undefined"!=typeof window?window:this,function(){function t(){}var e=t.prototype;return e.on=function(t,e){if(t&&e){var i=this._events=this._events||{},n=i[t]=i[t]||[];return-1==n.indexOf(e)&&n.push(e),this}},e.once=function(t,e){if(t&&e){this.on(t,e);var i=this._onceEvents=this._onceEvents||{},n=i[t]=i[t]||{};return n[e]=!0,this}},e.off=function(t,e){var i=this._events&&this._events[t];if(i&&i.length){var n=i.indexOf(e);return-1!=n&&i.splice(n,1),this}},e.emitEvent=function(t,e){var i=this._events&&this._events[t];if(i&&i.length){var n=0,o=i[n];e=e||[];for(var s=this._onceEvents&&this._onceEvents[t];o;){var r=s&&s[o];r&&(this.off(t,o),delete s[o]),o.apply(this,e),n+=r?0:1,o=i[n]}return this}},t}),function(t,e){"use strict";"function"==typeof define&&define.amd?define("get-size/get-size",[],function(){return e()}):"object"==typeof module&&module.exports?module.exports=e():t.getSize=e()}(window,function(){"use strict";function t(t){var e=parseFloat(t),i=-1==t.indexOf("%")&&!isNaN(e);return i&&e}function e(){}function i(){for(var t={width:0,height:0,innerWidth:0,innerHeight:0,outerWidth:0,outerHeight:0},e=0;h>e;e++){var i=u[e];t[i]=0}return t}function n(t){var e=getComputedStyle(t);return e||a("Style returned "+e+". Are you running this code in a hidden iframe on Firefox? See http://bit.ly/getsizebug1"),e}function o(){if(!d){d=!0;var e=document.createElement("div");e.style.width="200px",e.style.padding="1px 2px 3px 4px",e.style.borderStyle="solid",e.style.borderWidth="1px 2px 3px 4px",e.style.boxSizing="border-box";var i=document.body||document.documentElement;i.appendChild(e);var o=n(e);s.isBoxSizeOuter=r=200==t(o.width),i.removeChild(e)}}function s(e){if(o(),"string"==typeof e&&(e=document.querySelector(e)),e&&"object"==typeof e&&e.nodeType){var s=n(e);if("none"==s.display)return i();var a={};a.width=e.offsetWidth,a.height=e.offsetHeight;for(var d=a.isBorderBox="border-box"==s.boxSizing,l=0;h>l;l++){var f=u[l],c=s[f],m=parseFloat(c);a[f]=isNaN(m)?0:m}var p=a.paddingLeft+a.paddingRight,y=a.paddingTop+a.paddingBottom,g=a.marginLeft+a.marginRight,v=a.marginTop+a.marginBottom,_=a.borderLeftWidth+a.borderRightWidth,I=a.borderTopWidth+a.borderBottomWidth,z=d&&r,x=t(s.width);x!==!1&&(a.width=x+(z?0:p+_));var S=t(s.height);return S!==!1&&(a.height=S+(z?0:y+I)),a.innerWidth=a.width-(p+_),a.innerHeight=a.height-(y+I),a.outerWidth=a.width+g,a.outerHeight=a.height+v,a}}var r,a="undefined"==typeof console?e:function(t){console.error(t)},u=["paddingLeft","paddingRight","paddingTop","paddingBottom","marginLeft","marginRight","marginTop","marginBottom","borderLeftWidth","borderRightWidth","borderTopWidth","borderBottomWidth"],h=u.length,d=!1;return s}),function(t,e){"use strict";"function"==typeof define&&define.amd?define("desandro-matches-selector/matches-selector",e):"object"==typeof module&&module.exports?module.exports=e():t.matchesSelector=e()}(window,function(){"use strict";var t=function(){var t=Element.prototype;if(t.matches)return"matches";if(t.matchesSelector)return"matchesSelector";for(var e=["webkit","moz","ms","o"],i=0;i<e.length;i++){var n=e[i],o=n+"MatchesSelector";if(t[o])return o}}();return function(e,i){return e[t](i)}}),function(t,e){"function"==typeof define&&define.amd?define("fizzy-ui-utils/utils",["desandro-matches-selector/matches-selector"],function(i){return e(t,i)}):"object"==typeof module&&module.exports?module.exports=e(t,require("desandro-matches-selector")):t.fizzyUIUtils=e(t,t.matchesSelector)}(window,function(t,e){var i={};i.extend=function(t,e){for(var i in e)t[i]=e[i];return t},i.modulo=function(t,e){return(t%e+e)%e},i.makeArray=function(t){var e=[];if(Array.isArray(t))e=t;else if(t&&"number"==typeof t.length)for(var i=0;i<t.length;i++)e.push(t[i]);else e.push(t);return e},i.removeFrom=function(t,e){var i=t.indexOf(e);-1!=i&&t.splice(i,1)},i.getParent=function(t,i){for(;t!=document.body;)if(t=t.parentNode,e(t,i))return t},i.getQueryElement=function(t){return"string"==typeof t?document.querySelector(t):t},i.handleEvent=function(t){var e="on"+t.type;this[e]&&this[e](t)},i.filterFindElements=function(t,n){t=i.makeArray(t);var o=[];return t.forEach(function(t){if(t instanceof HTMLElement){if(!n)return void o.push(t);e(t,n)&&o.push(t);for(var i=t.querySelectorAll(n),s=0;s<i.length;s++)o.push(i[s])}}),o},i.debounceMethod=function(t,e,i){var n=t.prototype[e],o=e+"Timeout";t.prototype[e]=function(){var t=this[o];t&&clearTimeout(t);var e=arguments,s=this;this[o]=setTimeout(function(){n.apply(s,e),delete s[o]},i||100)}},i.docReady=function(t){var e=document.readyState;"complete"==e||"interactive"==e?t():document.addEventListener("DOMContentLoaded",t)},i.toDashed=function(t){return t.replace(/(.)([A-Z])/g,function(t,e,i){return e+"-"+i}).toLowerCase()};var n=t.console;return i.htmlInit=function(e,o){i.docReady(function(){var s=i.toDashed(o),r="data-"+s,a=document.querySelectorAll("["+r+"]"),u=document.querySelectorAll(".js-"+s),h=i.makeArray(a).concat(i.makeArray(u)),d=r+"-options",l=t.jQuery;h.forEach(function(t){var i,s=t.getAttribute(r)||t.getAttribute(d);try{i=s&&JSON.parse(s)}catch(a){return void(n&&n.error("Error parsing "+r+" on "+t.className+": "+a))}var u=new e(t,i);l&&l.data(t,o,u)})})},i}),function(t,e){"function"==typeof define&&define.amd?define("outlayer/item",["ev-emitter/ev-emitter","get-size/get-size"],e):"object"==typeof module&&module.exports?module.exports=e(require("ev-emitter"),require("get-size")):(t.Outlayer={},t.Outlayer.Item=e(t.EvEmitter,t.getSize))}(window,function(t,e){"use strict";function i(t){for(var e in t)return!1;return e=null,!0}function n(t,e){t&&(this.element=t,this.layout=e,this.position={x:0,y:0},this._create())}function o(t){return t.replace(/([A-Z])/g,function(t){return"-"+t.toLowerCase()})}var s=document.documentElement.style,r="string"==typeof s.transition?"transition":"WebkitTransition",a="string"==typeof s.transform?"transform":"WebkitTransform",u={WebkitTransition:"webkitTransitionEnd",transition:"transitionend"}[r],h={transform:a,transition:r,transitionDuration:r+"Duration",transitionProperty:r+"Property",transitionDelay:r+"Delay"},d=n.prototype=Object.create(t.prototype);d.constructor=n,d._create=function(){this._transn={ingProperties:{},clean:{},onEnd:{}},this.css({position:"absolute"})},d.handleEvent=function(t){var e="on"+t.type;this[e]&&this[e](t)},d.getSize=function(){this.size=e(this.element)},d.css=function(t){var e=this.element.style;for(var i in t){var n=h[i]||i;e[n]=t[i]}},d.getPosition=function(){var t=getComputedStyle(this.element),e=this.layout._getOption("originLeft"),i=this.layout._getOption("originTop"),n=t[e?"left":"right"],o=t[i?"top":"bottom"],s=this.layout.size,r=-1!=n.indexOf("%")?parseFloat(n)/100*s.width:parseInt(n,10),a=-1!=o.indexOf("%")?parseFloat(o)/100*s.height:parseInt(o,10);r=isNaN(r)?0:r,a=isNaN(a)?0:a,r-=e?s.paddingLeft:s.paddingRight,a-=i?s.paddingTop:s.paddingBottom,this.position.x=r,this.position.y=a},d.layoutPosition=function(){var t=this.layout.size,e={},i=this.layout._getOption("originLeft"),n=this.layout._getOption("originTop"),o=i?"paddingLeft":"paddingRight",s=i?"left":"right",r=i?"right":"left",a=this.position.x+t[o];e[s]=this.getXValue(a),e[r]="";var u=n?"paddingTop":"paddingBottom",h=n?"top":"bottom",d=n?"bottom":"top",l=this.position.y+t[u];e[h]=this.getYValue(l),e[d]="",this.css(e),this.emitEvent("layout",[this])},d.getXValue=function(t){var e=this.layout._getOption("horizontal");return this.layout.options.percentPosition&&!e?t/this.layout.size.width*100+"%":t+"px"},d.getYValue=function(t){var e=this.layout._getOption("horizontal");return this.layout.options.percentPosition&&e?t/this.layout.size.height*100+"%":t+"px"},d._transitionTo=function(t,e){this.getPosition();var i=this.position.x,n=this.position.y,o=parseInt(t,10),s=parseInt(e,10),r=o===this.position.x&&s===this.position.y;if(this.setPosition(t,e),r&&!this.isTransitioning)return void this.layoutPosition();var a=t-i,u=e-n,h={};h.transform=this.getTranslate(a,u),this.transition({to:h,onTransitionEnd:{transform:this.layoutPosition},isCleaning:!0})},d.getTranslate=function(t,e){var i=this.layout._getOption("originLeft"),n=this.layout._getOption("originTop");return t=i?t:-t,e=n?e:-e,"translate3d("+t+"px, "+e+"px, 0)"},d.goTo=function(t,e){this.setPosition(t,e),this.layoutPosition()},d.moveTo=d._transitionTo,d.setPosition=function(t,e){this.position.x=parseInt(t,10),this.position.y=parseInt(e,10)},d._nonTransition=function(t){this.css(t.to),t.isCleaning&&this._removeStyles(t.to);for(var e in t.onTransitionEnd)t.onTransitionEnd[e].call(this)},d.transition=function(t){if(!parseFloat(this.layout.options.transitionDuration))return void this._nonTransition(t);var e=this._transn;for(var i in t.onTransitionEnd)e.onEnd[i]=t.onTransitionEnd[i];for(i in t.to)e.ingProperties[i]=!0,t.isCleaning&&(e.clean[i]=!0);if(t.from){this.css(t.from);var n=this.element.offsetHeight;n=null}this.enableTransition(t.to),this.css(t.to),this.isTransitioning=!0};var l="opacity,"+o(a);d.enableTransition=function(){if(!this.isTransitioning){var t=this.layout.options.transitionDuration;t="number"==typeof t?t+"ms":t,this.css({transitionProperty:l,transitionDuration:t,transitionDelay:this.staggerDelay||0}),this.element.addEventListener(u,this,!1)}},d.onwebkitTransitionEnd=function(t){this.ontransitionend(t)},d.onotransitionend=function(t){this.ontransitionend(t)};var f={"-webkit-transform":"transform"};d.ontransitionend=function(t){if(t.target===this.element){var e=this._transn,n=f[t.propertyName]||t.propertyName;if(delete e.ingProperties[n],i(e.ingProperties)&&this.disableTransition(),n in e.clean&&(this.element.style[t.propertyName]="",delete e.clean[n]),n in e.onEnd){var o=e.onEnd[n];o.call(this),delete e.onEnd[n]}this.emitEvent("transitionEnd",[this])}},d.disableTransition=function(){this.removeTransitionStyles(),this.element.removeEventListener(u,this,!1),this.isTransitioning=!1},d._removeStyles=function(t){var e={};for(var i in t)e[i]="";this.css(e)};var c={transitionProperty:"",transitionDuration:"",transitionDelay:""};return d.removeTransitionStyles=function(){this.css(c)},d.stagger=function(t){t=isNaN(t)?0:t,this.staggerDelay=t+"ms"},d.removeElem=function(){this.element.parentNode.removeChild(this.element),this.css({display:""}),this.emitEvent("remove",[this])},d.remove=function(){return r&&parseFloat(this.layout.options.transitionDuration)?(this.once("transitionEnd",function(){this.removeElem()}),void this.hide()):void this.removeElem()},d.reveal=function(){delete this.isHidden,this.css({display:""});var t=this.layout.options,e={},i=this.getHideRevealTransitionEndProperty("visibleStyle");e[i]=this.onRevealTransitionEnd,this.transition({from:t.hiddenStyle,to:t.visibleStyle,isCleaning:!0,onTransitionEnd:e})},d.onRevealTransitionEnd=function(){this.isHidden||this.emitEvent("reveal")},d.getHideRevealTransitionEndProperty=function(t){var e=this.layout.options[t];if(e.opacity)return"opacity";for(var i in e)return i},d.hide=function(){this.isHidden=!0,this.css({display:""});var t=this.layout.options,e={},i=this.getHideRevealTransitionEndProperty("hiddenStyle");e[i]=this.onHideTransitionEnd,this.transition({from:t.visibleStyle,to:t.hiddenStyle,isCleaning:!0,onTransitionEnd:e})},d.onHideTransitionEnd=function(){this.isHidden&&(this.css({display:"none"}),this.emitEvent("hide"))},d.destroy=function(){this.css({position:"",left:"",right:"",top:"",bottom:"",transition:"",transform:""})},n}),function(t,e){"use strict";"function"==typeof define&&define.amd?define("outlayer/outlayer",["ev-emitter/ev-emitter","get-size/get-size","fizzy-ui-utils/utils","./item"],function(i,n,o,s){return e(t,i,n,o,s)}):"object"==typeof module&&module.exports?module.exports=e(t,require("ev-emitter"),require("get-size"),require("fizzy-ui-utils"),require("./item")):t.Outlayer=e(t,t.EvEmitter,t.getSize,t.fizzyUIUtils,t.Outlayer.Item)}(window,function(t,e,i,n,o){"use strict";function s(t,e){var i=n.getQueryElement(t);if(!i)return void(u&&u.error("Bad element for "+this.constructor.namespace+": "+(i||t)));this.element=i,h&&(this.$element=h(this.element)),this.options=n.extend({},this.constructor.defaults),this.option(e);var o=++l;this.element.outlayerGUID=o,f[o]=this,this._create();var s=this._getOption("initLayout");s&&this.layout()}function r(t){function e(){t.apply(this,arguments)}return e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e}function a(t){if("number"==typeof t)return t;var e=t.match(/(^\d*\.?\d*)(\w*)/),i=e&&e[1],n=e&&e[2];if(!i.length)return 0;i=parseFloat(i);var o=m[n]||1;return i*o}var u=t.console,h=t.jQuery,d=function(){},l=0,f={};s.namespace="outlayer",s.Item=o,s.defaults={containerStyle:{position:"relative"},initLayout:!0,originLeft:!0,originTop:!0,resize:!0,resizeContainer:!0,transitionDuration:"0.4s",hiddenStyle:{opacity:0,transform:"scale(0.001)"},visibleStyle:{opacity:1,transform:"scale(1)"}};var c=s.prototype;n.extend(c,e.prototype),c.option=function(t){n.extend(this.options,t)},c._getOption=function(t){var e=this.constructor.compatOptions[t];return e&&void 0!==this.options[e]?this.options[e]:this.options[t]},s.compatOptions={initLayout:"isInitLayout",horizontal:"isHorizontal",layoutInstant:"isLayoutInstant",originLeft:"isOriginLeft",originTop:"isOriginTop",resize:"isResizeBound",resizeContainer:"isResizingContainer"},c._create=function(){this.reloadItems(),this.stamps=[],this.stamp(this.options.stamp),n.extend(this.element.style,this.options.containerStyle);var t=this._getOption("resize");t&&this.bindResize()},c.reloadItems=function(){this.items=this._itemize(this.element.children)},c._itemize=function(t){for(var e=this._filterFindItemElements(t),i=this.constructor.Item,n=[],o=0;o<e.length;o++){var s=e[o],r=new i(s,this);n.push(r)}return n},c._filterFindItemElements=function(t){return n.filterFindElements(t,this.options.itemSelector)},c.getItemElements=function(){return this.items.map(function(t){return t.element})},c.layout=function(){this._resetLayout(),this._manageStamps();var t=this._getOption("layoutInstant"),e=void 0!==t?t:!this._isLayoutInited;this.layoutItems(this.items,e),this._isLayoutInited=!0},c._init=c.layout,c._resetLayout=function(){this.getSize()},c.getSize=function(){this.size=i(this.element)},c._getMeasurement=function(t,e){var n,o=this.options[t];o?("string"==typeof o?n=this.element.querySelector(o):o instanceof HTMLElement&&(n=o),this[t]=n?i(n)[e]:o):this[t]=0},c.layoutItems=function(t,e){t=this._getItemsForLayout(t),this._layoutItems(t,e),this._postLayout()},c._getItemsForLayout=function(t){return t.filter(function(t){return!t.isIgnored})},c._layoutItems=function(t,e){if(this._emitCompleteOnItems("layout",t),t&&t.length){var i=[];t.forEach(function(t){var n=this._getItemLayoutPosition(t);n.item=t,n.isInstant=e||t.isLayoutInstant,i.push(n)},this),this._processLayoutQueue(i)}},c._getItemLayoutPosition=function(){return{x:0,y:0}},c._processLayoutQueue=function(t){this.updateStagger(),t.forEach(function(t,e){this._positionItem(t.item,t.x,t.y,t.isInstant,e)},this)},c.updateStagger=function(){var t=this.options.stagger;return null===t||void 0===t?void(this.stagger=0):(this.stagger=a(t),this.stagger)},c._positionItem=function(t,e,i,n,o){n?t.goTo(e,i):(t.stagger(o*this.stagger),t.moveTo(e,i))},c._postLayout=function(){this.resizeContainer()},c.resizeContainer=function(){var t=this._getOption("resizeContainer");if(t){var e=this._getContainerSize();e&&(this._setContainerMeasure(e.width,!0),this._setContainerMeasure(e.height,!1))}},c._getContainerSize=d,c._setContainerMeasure=function(t,e){if(void 0!==t){var i=this.size;i.isBorderBox&&(t+=e?i.paddingLeft+i.paddingRight+i.borderLeftWidth+i.borderRightWidth:i.paddingBottom+i.paddingTop+i.borderTopWidth+i.borderBottomWidth),t=Math.max(t,0),this.element.style[e?"width":"height"]=t+"px"}},c._emitCompleteOnItems=function(t,e){function i(){o.dispatchEvent(t+"Complete",null,[e])}function n(){r++,r==s&&i()}var o=this,s=e.length;if(!e||!s)return void i();var r=0;e.forEach(function(e){e.once(t,n)})},c.dispatchEvent=function(t,e,i){var n=e?[e].concat(i):i;if(this.emitEvent(t,n),h)if(this.$element=this.$element||h(this.element),e){var o=h.Event(e);o.type=t,this.$element.trigger(o,i)}else this.$element.trigger(t,i)},c.ignore=function(t){var e=this.getItem(t);e&&(e.isIgnored=!0)},c.unignore=function(t){var e=this.getItem(t);e&&delete e.isIgnored},c.stamp=function(t){t=this._find(t),t&&(this.stamps=this.stamps.concat(t),t.forEach(this.ignore,this))},c.unstamp=function(t){t=this._find(t),t&&t.forEach(function(t){n.removeFrom(this.stamps,t),this.unignore(t)},this)},c._find=function(t){return t?("string"==typeof t&&(t=this.element.querySelectorAll(t)),t=n.makeArray(t)):void 0},c._manageStamps=function(){this.stamps&&this.stamps.length&&(this._getBoundingRect(),this.stamps.forEach(this._manageStamp,this))},c._getBoundingRect=function(){var t=this.element.getBoundingClientRect(),e=this.size;this._boundingRect={left:t.left+e.paddingLeft+e.borderLeftWidth,top:t.top+e.paddingTop+e.borderTopWidth,right:t.right-(e.paddingRight+e.borderRightWidth),bottom:t.bottom-(e.paddingBottom+e.borderBottomWidth)}},c._manageStamp=d,c._getElementOffset=function(t){var e=t.getBoundingClientRect(),n=this._boundingRect,o=i(t),s={left:e.left-n.left-o.marginLeft,top:e.top-n.top-o.marginTop,right:n.right-e.right-o.marginRight,bottom:n.bottom-e.bottom-o.marginBottom};return s},c.handleEvent=n.handleEvent,c.bindResize=function(){t.addEventListener("resize",this),this.isResizeBound=!0},c.unbindResize=function(){t.removeEventListener("resize",this),this.isResizeBound=!1},c.onresize=function(){this.resize()},n.debounceMethod(s,"onresize",100),c.resize=function(){this.isResizeBound&&this.needsResizeLayout()&&this.layout()},c.needsResizeLayout=function(){var t=i(this.element),e=this.size&&t;return e&&t.innerWidth!==this.size.innerWidth},c.addItems=function(t){var e=this._itemize(t);return e.length&&(this.items=this.items.concat(e)),e},c.appended=function(t){var e=this.addItems(t);e.length&&(this.layoutItems(e,!0),this.reveal(e))},c.prepended=function(t){var e=this._itemize(t);if(e.length){var i=this.items.slice(0);this.items=e.concat(i),this._resetLayout(),this._manageStamps(),this.layoutItems(e,!0),this.reveal(e),this.layoutItems(i)}},c.reveal=function(t){if(this._emitCompleteOnItems("reveal",t),t&&t.length){var e=this.updateStagger();t.forEach(function(t,i){t.stagger(i*e),t.reveal()})}},c.hide=function(t){if(this._emitCompleteOnItems("hide",t),t&&t.length){var e=this.updateStagger();t.forEach(function(t,i){t.stagger(i*e),t.hide()})}},c.revealItemElements=function(t){var e=this.getItems(t);this.reveal(e)},c.hideItemElements=function(t){var e=this.getItems(t);this.hide(e)},c.getItem=function(t){for(var e=0;e<this.items.length;e++){var i=this.items[e];if(i.element==t)return i}},c.getItems=function(t){t=n.makeArray(t);var e=[];return t.forEach(function(t){var i=this.getItem(t);i&&e.push(i)},this),e},c.remove=function(t){var e=this.getItems(t);this._emitCompleteOnItems("remove",e),e&&e.length&&e.forEach(function(t){t.remove(),n.removeFrom(this.items,t)},this)},c.destroy=function(){var t=this.element.style;t.height="",t.position="",t.width="",this.items.forEach(function(t){t.destroy()}),this.unbindResize();var e=this.element.outlayerGUID;delete f[e],delete this.element.outlayerGUID,h&&h.removeData(this.element,this.constructor.namespace)},s.data=function(t){t=n.getQueryElement(t);var e=t&&t.outlayerGUID;return e&&f[e]},s.create=function(t,e){var i=r(s);return i.defaults=n.extend({},s.defaults),n.extend(i.defaults,e),i.compatOptions=n.extend({},s.compatOptions),i.namespace=t,i.data=s.data,i.Item=r(o),n.htmlInit(i,t),h&&h.bridget&&h.bridget(t,i),i};var m={ms:1,s:1e3};return s.Item=o,s}),function(t,e){"function"==typeof define&&define.amd?define("isotope/js/item",["outlayer/outlayer"],e):"object"==typeof module&&module.exports?module.exports=e(require("outlayer")):(t.Isotope=t.Isotope||{},t.Isotope.Item=e(t.Outlayer))}(window,function(t){"use strict";function e(){t.Item.apply(this,arguments)}var i=e.prototype=Object.create(t.Item.prototype),n=i._create;i._create=function(){this.id=this.layout.itemGUID++,n.call(this),this.sortData={}},i.updateSortData=function(){if(!this.isIgnored){this.sortData.id=this.id,this.sortData["original-order"]=this.id,this.sortData.random=Math.random();var t=this.layout.options.getSortData,e=this.layout._sorters;for(var i in t){var n=e[i];this.sortData[i]=n(this.element,this)}}};var o=i.destroy;return i.destroy=function(){o.apply(this,arguments),this.css({display:""})},e}),function(t,e){"function"==typeof define&&define.amd?define("isotope/js/layout-mode",["get-size/get-size","outlayer/outlayer"],e):"object"==typeof module&&module.exports?module.exports=e(require("get-size"),require("outlayer")):(t.Isotope=t.Isotope||{},t.Isotope.LayoutMode=e(t.getSize,t.Outlayer))}(window,function(t,e){"use strict";function i(t){this.isotope=t,t&&(this.options=t.options[this.namespace],this.element=t.element,this.items=t.filteredItems,this.size=t.size)}var n=i.prototype,o=["_resetLayout","_getItemLayoutPosition","_manageStamp","_getContainerSize","_getElementOffset","needsResizeLayout","_getOption"];return o.forEach(function(t){n[t]=function(){return e.prototype[t].apply(this.isotope,arguments)}}),n.needsVerticalResizeLayout=function(){var e=t(this.isotope.element),i=this.isotope.size&&e;return i&&e.innerHeight!=this.isotope.size.innerHeight},n._getMeasurement=function(){this.isotope._getMeasurement.apply(this,arguments)},n.getColumnWidth=function(){this.getSegmentSize("column","Width")},n.getRowHeight=function(){this.getSegmentSize("row","Height")},n.getSegmentSize=function(t,e){var i=t+e,n="outer"+e;if(this._getMeasurement(i,n),!this[i]){var o=this.getFirstItemSize();this[i]=o&&o[n]||this.isotope.size["inner"+e]}},n.getFirstItemSize=function(){var e=this.isotope.filteredItems[0];return e&&e.element&&t(e.element)},n.layout=function(){this.isotope.layout.apply(this.isotope,arguments)},n.getSize=function(){this.isotope.getSize(),this.size=this.isotope.size},i.modes={},i.create=function(t,e){function o(){i.apply(this,arguments)}return o.prototype=Object.create(n),o.prototype.constructor=o,e&&(o.options=e),o.prototype.namespace=t,i.modes[t]=o,o},i}),function(t,e){"function"==typeof define&&define.amd?define("masonry/masonry",["outlayer/outlayer","get-size/get-size"],e):"object"==typeof module&&module.exports?module.exports=e(require("outlayer"),require("get-size")):t.Masonry=e(t.Outlayer,t.getSize)}(window,function(t,e){var i=t.create("masonry");return i.compatOptions.fitWidth="isFitWidth",i.prototype._resetLayout=function(){this.getSize(),this._getMeasurement("columnWidth","outerWidth"),this._getMeasurement("gutter","outerWidth"),this.measureColumns(),this.colYs=[];for(var t=0;t<this.cols;t++)this.colYs.push(0);this.maxY=0},i.prototype.measureColumns=function(){if(this.getContainerWidth(),!this.columnWidth){var t=this.items[0],i=t&&t.element;this.columnWidth=i&&e(i).outerWidth||this.containerWidth}var n=this.columnWidth+=this.gutter,o=this.containerWidth+this.gutter,s=o/n,r=n-o%n,a=r&&1>r?"round":"floor";s=Math[a](s),this.cols=Math.max(s,1)},i.prototype.getContainerWidth=function(){var t=this._getOption("fitWidth"),i=t?this.element.parentNode:this.element,n=e(i);this.containerWidth=n&&n.innerWidth},i.prototype._getItemLayoutPosition=function(t){t.getSize();var e=t.size.outerWidth%this.columnWidth,i=e&&1>e?"round":"ceil",n=Math[i](t.size.outerWidth/this.columnWidth);n=Math.min(n,this.cols);for(var o=this._getColGroup(n),s=Math.min.apply(Math,o),r=o.indexOf(s),a={x:this.columnWidth*r,y:s},u=s+t.size.outerHeight,h=this.cols+1-o.length,d=0;h>d;d++)this.colYs[r+d]=u;return a},i.prototype._getColGroup=function(t){if(2>t)return this.colYs;for(var e=[],i=this.cols+1-t,n=0;i>n;n++){var o=this.colYs.slice(n,n+t);e[n]=Math.max.apply(Math,o)}return e},i.prototype._manageStamp=function(t){var i=e(t),n=this._getElementOffset(t),o=this._getOption("originLeft"),s=o?n.left:n.right,r=s+i.outerWidth,a=Math.floor(s/this.columnWidth);a=Math.max(0,a);var u=Math.floor(r/this.columnWidth);u-=r%this.columnWidth?0:1,u=Math.min(this.cols-1,u);for(var h=this._getOption("originTop"),d=(h?n.top:n.bottom)+i.outerHeight,l=a;u>=l;l++)this.colYs[l]=Math.max(d,this.colYs[l])},i.prototype._getContainerSize=function(){this.maxY=Math.max.apply(Math,this.colYs);var t={height:this.maxY};return this._getOption("fitWidth")&&(t.width=this._getContainerFitWidth()),t},i.prototype._getContainerFitWidth=function(){for(var t=0,e=this.cols;--e&&0===this.colYs[e];)t++;return(this.cols-t)*this.columnWidth-this.gutter},i.prototype.needsResizeLayout=function(){var t=this.containerWidth;return this.getContainerWidth(),t!=this.containerWidth},i}),function(t,e){"function"==typeof define&&define.amd?define("isotope/js/layout-modes/masonry",["../layout-mode","masonry/masonry"],e):"object"==typeof module&&module.exports?module.exports=e(require("../layout-mode"),require("masonry-layout")):e(t.Isotope.LayoutMode,t.Masonry)}(window,function(t,e){"use strict";var i=t.create("masonry"),n=i.prototype,o={_getElementOffset:!0,layout:!0,_getMeasurement:!0};for(var s in e.prototype)o[s]||(n[s]=e.prototype[s]);var r=n.measureColumns;n.measureColumns=function(){this.items=this.isotope.filteredItems,r.call(this)};var a=n._getOption;return n._getOption=function(t){return"fitWidth"==t?void 0!==this.options.isFitWidth?this.options.isFitWidth:this.options.fitWidth:a.apply(this.isotope,arguments)},i}),function(t,e){"function"==typeof define&&define.amd?define("isotope/js/layout-modes/fit-rows",["../layout-mode"],e):"object"==typeof exports?module.exports=e(require("../layout-mode")):e(t.Isotope.LayoutMode)}(window,function(t){"use strict";var e=t.create("fitRows"),i=e.prototype;return i._resetLayout=function(){this.x=0,this.y=0,this.maxY=0,this._getMeasurement("gutter","outerWidth")},i._getItemLayoutPosition=function(t){t.getSize();var e=t.size.outerWidth+this.gutter,i=this.isotope.size.innerWidth+this.gutter;0!==this.x&&e+this.x>i&&(this.x=0,this.y=this.maxY);var n={x:this.x,y:this.y};return this.maxY=Math.max(this.maxY,this.y+t.size.outerHeight),this.x+=e,n},i._getContainerSize=function(){return{height:this.maxY}},e}),function(t,e){"function"==typeof define&&define.amd?define("isotope/js/layout-modes/vertical",["../layout-mode"],e):"object"==typeof module&&module.exports?module.exports=e(require("../layout-mode")):e(t.Isotope.LayoutMode)}(window,function(t){"use strict";var e=t.create("vertical",{horizontalAlignment:0}),i=e.prototype;return i._resetLayout=function(){this.y=0},i._getItemLayoutPosition=function(t){t.getSize();var e=(this.isotope.size.innerWidth-t.size.outerWidth)*this.options.horizontalAlignment,i=this.y;return this.y+=t.size.outerHeight,{x:e,y:i}},i._getContainerSize=function(){return{height:this.y}},e}),function(t,e){"function"==typeof define&&define.amd?define(["outlayer/outlayer","get-size/get-size","desandro-matches-selector/matches-selector","fizzy-ui-utils/utils","isotope/js/item","isotope/js/layout-mode","isotope/js/layout-modes/masonry","isotope/js/layout-modes/fit-rows","isotope/js/layout-modes/vertical"],function(i,n,o,s,r,a){return e(t,i,n,o,s,r,a)}):"object"==typeof module&&module.exports?module.exports=e(t,require("outlayer"),require("get-size"),require("desandro-matches-selector"),require("fizzy-ui-utils"),require("isotope/js/item"),require("isotope/js/layout-mode"),require("isotope/js/layout-modes/masonry"),require("isotope/js/layout-modes/fit-rows"),require("isotope/js/layout-modes/vertical")):t.Isotope=e(t,t.Outlayer,t.getSize,t.matchesSelector,t.fizzyUIUtils,t.Isotope.Item,t.Isotope.LayoutMode)}(window,function(t,e,i,n,o,s,r){function a(t,e){return function(i,n){for(var o=0;o<t.length;o++){var s=t[o],r=i.sortData[s],a=n.sortData[s];if(r>a||a>r){var u=void 0!==e[s]?e[s]:e,h=u?1:-1;return(r>a?1:-1)*h}}return 0}}var u=t.jQuery,h=String.prototype.trim?function(t){return t.trim()}:function(t){return t.replace(/^\s+|\s+$/g,"")},d=e.create("isotope",{layoutMode:"masonry",isJQueryFiltering:!0,sortAscending:!0});d.Item=s,d.LayoutMode=r;var l=d.prototype;l._create=function(){this.itemGUID=0,this._sorters={},this._getSorters(),e.prototype._create.call(this),this.modes={},this.filteredItems=this.items,this.sortHistory=["original-order"];for(var t in r.modes)this._initLayoutMode(t)},l.reloadItems=function(){this.itemGUID=0,e.prototype.reloadItems.call(this)},l._itemize=function(){for(var t=e.prototype._itemize.apply(this,arguments),i=0;i<t.length;i++){var n=t[i];n.id=this.itemGUID++}return this._updateItemsSortData(t),t},l._initLayoutMode=function(t){var e=r.modes[t],i=this.options[t]||{};this.options[t]=e.options?o.extend(e.options,i):i,this.modes[t]=new e(this)},l.layout=function(){return!this._isLayoutInited&&this._getOption("initLayout")?void this.arrange():void this._layout()},l._layout=function(){var t=this._getIsInstant();this._resetLayout(),this._manageStamps(),this.layoutItems(this.filteredItems,t),this._isLayoutInited=!0},l.arrange=function(t){this.option(t),this._getIsInstant();var e=this._filter(this.items);this.filteredItems=e.matches,this._bindArrangeComplete(),this._isInstant?this._noTransition(this._hideReveal,[e]):this._hideReveal(e),this._sort(),this._layout()},l._init=l.arrange,l._hideReveal=function(t){this.reveal(t.needReveal),this.hide(t.needHide)},l._getIsInstant=function(){var t=this._getOption("layoutInstant"),e=void 0!==t?t:!this._isLayoutInited;return this._isInstant=e,e},l._bindArrangeComplete=function(){function t(){e&&i&&n&&o.dispatchEvent("arrangeComplete",null,[o.filteredItems])}var e,i,n,o=this;this.once("layoutComplete",function(){e=!0,t()}),this.once("hideComplete",function(){i=!0,t()}),this.once("revealComplete",function(){n=!0,t()})},l._filter=function(t){var e=this.options.filter;e=e||"*";for(var i=[],n=[],o=[],s=this._getFilterTest(e),r=0;r<t.length;r++){var a=t[r];if(!a.isIgnored){var u=s(a);u&&i.push(a),u&&a.isHidden?n.push(a):u||a.isHidden||o.push(a)}}return{matches:i,needReveal:n,needHide:o}},l._getFilterTest=function(t){return u&&this.options.isJQueryFiltering?function(e){return u(e.element).is(t)}:"function"==typeof t?function(e){return t(e.element)}:function(e){return n(e.element,t)}},l.updateSortData=function(t){var e;t?(t=o.makeArray(t),e=this.getItems(t)):e=this.items,this._getSorters(),this._updateItemsSortData(e)},l._getSorters=function(){var t=this.options.getSortData;for(var e in t){var i=t[e];this._sorters[e]=f(i)}},l._updateItemsSortData=function(t){for(var e=t&&t.length,i=0;e&&e>i;i++){var n=t[i];n.updateSortData()}};var f=function(){function t(t){if("string"!=typeof t)return t;var i=h(t).split(" "),n=i[0],o=n.match(/^\[(.+)\]$/),s=o&&o[1],r=e(s,n),a=d.sortDataParsers[i[1]];
return t=a?function(t){return t&&a(r(t))}:function(t){return t&&r(t)}}function e(t,e){return t?function(e){return e.getAttribute(t)}:function(t){var i=t.querySelector(e);return i&&i.textContent}}return t}();d.sortDataParsers={parseInt:function(t){return parseInt(t,10)},parseFloat:function(t){return parseFloat(t)}},l._sort=function(){var t=this.options.sortBy;if(t){var e=[].concat.apply(t,this.sortHistory),i=a(e,this.options.sortAscending);this.filteredItems.sort(i),t!=this.sortHistory[0]&&this.sortHistory.unshift(t)}},l._mode=function(){var t=this.options.layoutMode,e=this.modes[t];if(!e)throw new Error("No layout mode: "+t);return e.options=this.options[t],e},l._resetLayout=function(){e.prototype._resetLayout.call(this),this._mode()._resetLayout()},l._getItemLayoutPosition=function(t){return this._mode()._getItemLayoutPosition(t)},l._manageStamp=function(t){this._mode()._manageStamp(t)},l._getContainerSize=function(){return this._mode()._getContainerSize()},l.needsResizeLayout=function(){return this._mode().needsResizeLayout()},l.appended=function(t){var e=this.addItems(t);if(e.length){var i=this._filterRevealAdded(e);this.filteredItems=this.filteredItems.concat(i)}},l.prepended=function(t){var e=this._itemize(t);if(e.length){this._resetLayout(),this._manageStamps();var i=this._filterRevealAdded(e);this.layoutItems(this.filteredItems),this.filteredItems=i.concat(this.filteredItems),this.items=e.concat(this.items)}},l._filterRevealAdded=function(t){var e=this._filter(t);return this.hide(e.needHide),this.reveal(e.matches),this.layoutItems(e.matches,!0),e.matches},l.insert=function(t){var e=this.addItems(t);if(e.length){var i,n,o=e.length;for(i=0;o>i;i++)n=e[i],this.element.appendChild(n.element);var s=this._filter(e).matches;for(i=0;o>i;i++)e[i].isLayoutInstant=!0;for(this.arrange(),i=0;o>i;i++)delete e[i].isLayoutInstant;this.reveal(s)}};var c=l.remove;return l.remove=function(t){t=o.makeArray(t);var e=this.getItems(t);c.call(this,t);for(var i=e&&e.length,n=0;i&&i>n;n++){var s=e[n];o.removeFrom(this.filteredItems,s)}},l.shuffle=function(){for(var t=0;t<this.items.length;t++){var e=this.items[t];e.sortData.random=Math.random()}this.options.sortBy="random",this._sort(),this._layout()},l._noTransition=function(t,e){var i=this.options.transitionDuration;this.options.transitionDuration=0;var n=t.apply(this,e);return this.options.transitionDuration=i,n},l.getFilteredItemElements=function(){return this.filteredItems.map(function(t){return t.element})},d});;
/*!
 * VERSION: 1.19.0
 * DATE: 2016-07-14
 * UPDATES AND DOCS AT: http://greensock.com
 * 
 * Includes all of the following: TweenLite, TweenMax, TimelineLite, TimelineMax, EasePack, CSSPlugin, RoundPropsPlugin, BezierPlugin, AttrPlugin, DirectionalRotationPlugin
 *
 * @license Copyright (c) 2008-2016, GreenSock. All rights reserved.
 * This work is subject to the terms at http://greensock.com/standard-license or for
 * Club GreenSock members, the software agreement that was issued with your membership.
 * 
 * @author: Jack Doyle, jack@greensock.com
 **/
var _gsScope="undefined"!=typeof module&&module.exports&&"undefined"!=typeof global?global:this||window;(_gsScope._gsQueue||(_gsScope._gsQueue=[])).push(function(){"use strict";_gsScope._gsDefine("TweenMax",["core.Animation","core.SimpleTimeline","TweenLite"],function(a,b,c){var d=function(a){var b,c=[],d=a.length;for(b=0;b!==d;c.push(a[b++]));return c},e=function(a,b,c){var d,e,f=a.cycle;for(d in f)e=f[d],a[d]="function"==typeof e?e(c,b[c]):e[c%e.length];delete a.cycle},f=function(a,b,d){c.call(this,a,b,d),this._cycle=0,this._yoyo=this.vars.yoyo===!0,this._repeat=this.vars.repeat||0,this._repeatDelay=this.vars.repeatDelay||0,this._dirty=!0,this.render=f.prototype.render},g=1e-10,h=c._internals,i=h.isSelector,j=h.isArray,k=f.prototype=c.to({},.1,{}),l=[];f.version="1.19.0",k.constructor=f,k.kill()._gc=!1,f.killTweensOf=f.killDelayedCallsTo=c.killTweensOf,f.getTweensOf=c.getTweensOf,f.lagSmoothing=c.lagSmoothing,f.ticker=c.ticker,f.render=c.render,k.invalidate=function(){return this._yoyo=this.vars.yoyo===!0,this._repeat=this.vars.repeat||0,this._repeatDelay=this.vars.repeatDelay||0,this._uncache(!0),c.prototype.invalidate.call(this)},k.updateTo=function(a,b){var d,e=this.ratio,f=this.vars.immediateRender||a.immediateRender;b&&this._startTime<this._timeline._time&&(this._startTime=this._timeline._time,this._uncache(!1),this._gc?this._enabled(!0,!1):this._timeline.insert(this,this._startTime-this._delay));for(d in a)this.vars[d]=a[d];if(this._initted||f)if(b)this._initted=!1,f&&this.render(0,!0,!0);else if(this._gc&&this._enabled(!0,!1),this._notifyPluginsOfEnabled&&this._firstPT&&c._onPluginEvent("_onDisable",this),this._time/this._duration>.998){var g=this._totalTime;this.render(0,!0,!1),this._initted=!1,this.render(g,!0,!1)}else if(this._initted=!1,this._init(),this._time>0||f)for(var h,i=1/(1-e),j=this._firstPT;j;)h=j.s+j.c,j.c*=i,j.s=h-j.c,j=j._next;return this},k.render=function(a,b,c){this._initted||0===this._duration&&this.vars.repeat&&this.invalidate();var d,e,f,i,j,k,l,m,n=this._dirty?this.totalDuration():this._totalDuration,o=this._time,p=this._totalTime,q=this._cycle,r=this._duration,s=this._rawPrevTime;if(a>=n-1e-7?(this._totalTime=n,this._cycle=this._repeat,this._yoyo&&0!==(1&this._cycle)?(this._time=0,this.ratio=this._ease._calcEnd?this._ease.getRatio(0):0):(this._time=r,this.ratio=this._ease._calcEnd?this._ease.getRatio(1):1),this._reversed||(d=!0,e="onComplete",c=c||this._timeline.autoRemoveChildren),0===r&&(this._initted||!this.vars.lazy||c)&&(this._startTime===this._timeline._duration&&(a=0),(0>s||0>=a&&a>=-1e-7||s===g&&"isPause"!==this.data)&&s!==a&&(c=!0,s>g&&(e="onReverseComplete")),this._rawPrevTime=m=!b||a||s===a?a:g)):1e-7>a?(this._totalTime=this._time=this._cycle=0,this.ratio=this._ease._calcEnd?this._ease.getRatio(0):0,(0!==p||0===r&&s>0)&&(e="onReverseComplete",d=this._reversed),0>a&&(this._active=!1,0===r&&(this._initted||!this.vars.lazy||c)&&(s>=0&&(c=!0),this._rawPrevTime=m=!b||a||s===a?a:g)),this._initted||(c=!0)):(this._totalTime=this._time=a,0!==this._repeat&&(i=r+this._repeatDelay,this._cycle=this._totalTime/i>>0,0!==this._cycle&&this._cycle===this._totalTime/i&&a>=p&&this._cycle--,this._time=this._totalTime-this._cycle*i,this._yoyo&&0!==(1&this._cycle)&&(this._time=r-this._time),this._time>r?this._time=r:this._time<0&&(this._time=0)),this._easeType?(j=this._time/r,k=this._easeType,l=this._easePower,(1===k||3===k&&j>=.5)&&(j=1-j),3===k&&(j*=2),1===l?j*=j:2===l?j*=j*j:3===l?j*=j*j*j:4===l&&(j*=j*j*j*j),1===k?this.ratio=1-j:2===k?this.ratio=j:this._time/r<.5?this.ratio=j/2:this.ratio=1-j/2):this.ratio=this._ease.getRatio(this._time/r)),o===this._time&&!c&&q===this._cycle)return void(p!==this._totalTime&&this._onUpdate&&(b||this._callback("onUpdate")));if(!this._initted){if(this._init(),!this._initted||this._gc)return;if(!c&&this._firstPT&&(this.vars.lazy!==!1&&this._duration||this.vars.lazy&&!this._duration))return this._time=o,this._totalTime=p,this._rawPrevTime=s,this._cycle=q,h.lazyTweens.push(this),void(this._lazy=[a,b]);this._time&&!d?this.ratio=this._ease.getRatio(this._time/r):d&&this._ease._calcEnd&&(this.ratio=this._ease.getRatio(0===this._time?0:1))}for(this._lazy!==!1&&(this._lazy=!1),this._active||!this._paused&&this._time!==o&&a>=0&&(this._active=!0),0===p&&(2===this._initted&&a>0&&this._init(),this._startAt&&(a>=0?this._startAt.render(a,b,c):e||(e="_dummyGS")),this.vars.onStart&&(0!==this._totalTime||0===r)&&(b||this._callback("onStart"))),f=this._firstPT;f;)f.f?f.t[f.p](f.c*this.ratio+f.s):f.t[f.p]=f.c*this.ratio+f.s,f=f._next;this._onUpdate&&(0>a&&this._startAt&&this._startTime&&this._startAt.render(a,b,c),b||(this._totalTime!==p||e)&&this._callback("onUpdate")),this._cycle!==q&&(b||this._gc||this.vars.onRepeat&&this._callback("onRepeat")),e&&(!this._gc||c)&&(0>a&&this._startAt&&!this._onUpdate&&this._startTime&&this._startAt.render(a,b,c),d&&(this._timeline.autoRemoveChildren&&this._enabled(!1,!1),this._active=!1),!b&&this.vars[e]&&this._callback(e),0===r&&this._rawPrevTime===g&&m!==g&&(this._rawPrevTime=0))},f.to=function(a,b,c){return new f(a,b,c)},f.from=function(a,b,c){return c.runBackwards=!0,c.immediateRender=0!=c.immediateRender,new f(a,b,c)},f.fromTo=function(a,b,c,d){return d.startAt=c,d.immediateRender=0!=d.immediateRender&&0!=c.immediateRender,new f(a,b,d)},f.staggerTo=f.allTo=function(a,b,g,h,k,m,n){h=h||0;var o,p,q,r,s=0,t=[],u=function(){g.onComplete&&g.onComplete.apply(g.onCompleteScope||this,arguments),k.apply(n||g.callbackScope||this,m||l)},v=g.cycle,w=g.startAt&&g.startAt.cycle;for(j(a)||("string"==typeof a&&(a=c.selector(a)||a),i(a)&&(a=d(a))),a=a||[],0>h&&(a=d(a),a.reverse(),h*=-1),o=a.length-1,q=0;o>=q;q++){p={};for(r in g)p[r]=g[r];if(v&&(e(p,a,q),null!=p.duration&&(b=p.duration,delete p.duration)),w){w=p.startAt={};for(r in g.startAt)w[r]=g.startAt[r];e(p.startAt,a,q)}p.delay=s+(p.delay||0),q===o&&k&&(p.onComplete=u),t[q]=new f(a[q],b,p),s+=h}return t},f.staggerFrom=f.allFrom=function(a,b,c,d,e,g,h){return c.runBackwards=!0,c.immediateRender=0!=c.immediateRender,f.staggerTo(a,b,c,d,e,g,h)},f.staggerFromTo=f.allFromTo=function(a,b,c,d,e,g,h,i){return d.startAt=c,d.immediateRender=0!=d.immediateRender&&0!=c.immediateRender,f.staggerTo(a,b,d,e,g,h,i)},f.delayedCall=function(a,b,c,d,e){return new f(b,0,{delay:a,onComplete:b,onCompleteParams:c,callbackScope:d,onReverseComplete:b,onReverseCompleteParams:c,immediateRender:!1,useFrames:e,overwrite:0})},f.set=function(a,b){return new f(a,0,b)},f.isTweening=function(a){return c.getTweensOf(a,!0).length>0};var m=function(a,b){for(var d=[],e=0,f=a._first;f;)f instanceof c?d[e++]=f:(b&&(d[e++]=f),d=d.concat(m(f,b)),e=d.length),f=f._next;return d},n=f.getAllTweens=function(b){return m(a._rootTimeline,b).concat(m(a._rootFramesTimeline,b))};f.killAll=function(a,c,d,e){null==c&&(c=!0),null==d&&(d=!0);var f,g,h,i=n(0!=e),j=i.length,k=c&&d&&e;for(h=0;j>h;h++)g=i[h],(k||g instanceof b||(f=g.target===g.vars.onComplete)&&d||c&&!f)&&(a?g.totalTime(g._reversed?0:g.totalDuration()):g._enabled(!1,!1))},f.killChildTweensOf=function(a,b){if(null!=a){var e,g,k,l,m,n=h.tweenLookup;if("string"==typeof a&&(a=c.selector(a)||a),i(a)&&(a=d(a)),j(a))for(l=a.length;--l>-1;)f.killChildTweensOf(a[l],b);else{e=[];for(k in n)for(g=n[k].target.parentNode;g;)g===a&&(e=e.concat(n[k].tweens)),g=g.parentNode;for(m=e.length,l=0;m>l;l++)b&&e[l].totalTime(e[l].totalDuration()),e[l]._enabled(!1,!1)}}};var o=function(a,c,d,e){c=c!==!1,d=d!==!1,e=e!==!1;for(var f,g,h=n(e),i=c&&d&&e,j=h.length;--j>-1;)g=h[j],(i||g instanceof b||(f=g.target===g.vars.onComplete)&&d||c&&!f)&&g.paused(a)};return f.pauseAll=function(a,b,c){o(!0,a,b,c)},f.resumeAll=function(a,b,c){o(!1,a,b,c)},f.globalTimeScale=function(b){var d=a._rootTimeline,e=c.ticker.time;return arguments.length?(b=b||g,d._startTime=e-(e-d._startTime)*d._timeScale/b,d=a._rootFramesTimeline,e=c.ticker.frame,d._startTime=e-(e-d._startTime)*d._timeScale/b,d._timeScale=a._rootTimeline._timeScale=b,b):d._timeScale},k.progress=function(a,b){return arguments.length?this.totalTime(this.duration()*(this._yoyo&&0!==(1&this._cycle)?1-a:a)+this._cycle*(this._duration+this._repeatDelay),b):this._time/this.duration()},k.totalProgress=function(a,b){return arguments.length?this.totalTime(this.totalDuration()*a,b):this._totalTime/this.totalDuration()},k.time=function(a,b){return arguments.length?(this._dirty&&this.totalDuration(),a>this._duration&&(a=this._duration),this._yoyo&&0!==(1&this._cycle)?a=this._duration-a+this._cycle*(this._duration+this._repeatDelay):0!==this._repeat&&(a+=this._cycle*(this._duration+this._repeatDelay)),this.totalTime(a,b)):this._time},k.duration=function(b){return arguments.length?a.prototype.duration.call(this,b):this._duration},k.totalDuration=function(a){return arguments.length?-1===this._repeat?this:this.duration((a-this._repeat*this._repeatDelay)/(this._repeat+1)):(this._dirty&&(this._totalDuration=-1===this._repeat?999999999999:this._duration*(this._repeat+1)+this._repeatDelay*this._repeat,this._dirty=!1),this._totalDuration)},k.repeat=function(a){return arguments.length?(this._repeat=a,this._uncache(!0)):this._repeat},k.repeatDelay=function(a){return arguments.length?(this._repeatDelay=a,this._uncache(!0)):this._repeatDelay},k.yoyo=function(a){return arguments.length?(this._yoyo=a,this):this._yoyo},f},!0),_gsScope._gsDefine("TimelineLite",["core.Animation","core.SimpleTimeline","TweenLite"],function(a,b,c){var d=function(a){b.call(this,a),this._labels={},this.autoRemoveChildren=this.vars.autoRemoveChildren===!0,this.smoothChildTiming=this.vars.smoothChildTiming===!0,this._sortChildren=!0,this._onUpdate=this.vars.onUpdate;var c,d,e=this.vars;for(d in e)c=e[d],i(c)&&-1!==c.join("").indexOf("{self}")&&(e[d]=this._swapSelfInParams(c));i(e.tweens)&&this.add(e.tweens,0,e.align,e.stagger)},e=1e-10,f=c._internals,g=d._internals={},h=f.isSelector,i=f.isArray,j=f.lazyTweens,k=f.lazyRender,l=_gsScope._gsDefine.globals,m=function(a){var b,c={};for(b in a)c[b]=a[b];return c},n=function(a,b,c){var d,e,f=a.cycle;for(d in f)e=f[d],a[d]="function"==typeof e?e.call(b[c],c):e[c%e.length];delete a.cycle},o=g.pauseCallback=function(){},p=function(a){var b,c=[],d=a.length;for(b=0;b!==d;c.push(a[b++]));return c},q=d.prototype=new b;return d.version="1.19.0",q.constructor=d,q.kill()._gc=q._forcingPlayhead=q._hasPause=!1,q.to=function(a,b,d,e){var f=d.repeat&&l.TweenMax||c;return b?this.add(new f(a,b,d),e):this.set(a,d,e)},q.from=function(a,b,d,e){return this.add((d.repeat&&l.TweenMax||c).from(a,b,d),e)},q.fromTo=function(a,b,d,e,f){var g=e.repeat&&l.TweenMax||c;return b?this.add(g.fromTo(a,b,d,e),f):this.set(a,e,f)},q.staggerTo=function(a,b,e,f,g,i,j,k){var l,o,q=new d({onComplete:i,onCompleteParams:j,callbackScope:k,smoothChildTiming:this.smoothChildTiming}),r=e.cycle;for("string"==typeof a&&(a=c.selector(a)||a),a=a||[],h(a)&&(a=p(a)),f=f||0,0>f&&(a=p(a),a.reverse(),f*=-1),o=0;o<a.length;o++)l=m(e),l.startAt&&(l.startAt=m(l.startAt),l.startAt.cycle&&n(l.startAt,a,o)),r&&(n(l,a,o),null!=l.duration&&(b=l.duration,delete l.duration)),q.to(a[o],b,l,o*f);return this.add(q,g)},q.staggerFrom=function(a,b,c,d,e,f,g,h){return c.immediateRender=0!=c.immediateRender,c.runBackwards=!0,this.staggerTo(a,b,c,d,e,f,g,h)},q.staggerFromTo=function(a,b,c,d,e,f,g,h,i){return d.startAt=c,d.immediateRender=0!=d.immediateRender&&0!=c.immediateRender,this.staggerTo(a,b,d,e,f,g,h,i)},q.call=function(a,b,d,e){return this.add(c.delayedCall(0,a,b,d),e)},q.set=function(a,b,d){return d=this._parseTimeOrLabel(d,0,!0),null==b.immediateRender&&(b.immediateRender=d===this._time&&!this._paused),this.add(new c(a,0,b),d)},d.exportRoot=function(a,b){a=a||{},null==a.smoothChildTiming&&(a.smoothChildTiming=!0);var e,f,g=new d(a),h=g._timeline;for(null==b&&(b=!0),h._remove(g,!0),g._startTime=0,g._rawPrevTime=g._time=g._totalTime=h._time,e=h._first;e;)f=e._next,b&&e instanceof c&&e.target===e.vars.onComplete||g.add(e,e._startTime-e._delay),e=f;return h.add(g,0),g},q.add=function(e,f,g,h){var j,k,l,m,n,o;if("number"!=typeof f&&(f=this._parseTimeOrLabel(f,0,!0,e)),!(e instanceof a)){if(e instanceof Array||e&&e.push&&i(e)){for(g=g||"normal",h=h||0,j=f,k=e.length,l=0;k>l;l++)i(m=e[l])&&(m=new d({tweens:m})),this.add(m,j),"string"!=typeof m&&"function"!=typeof m&&("sequence"===g?j=m._startTime+m.totalDuration()/m._timeScale:"start"===g&&(m._startTime-=m.delay())),j+=h;return this._uncache(!0)}if("string"==typeof e)return this.addLabel(e,f);if("function"!=typeof e)throw"Cannot add "+e+" into the timeline; it is not a tween, timeline, function, or string.";e=c.delayedCall(0,e)}if(b.prototype.add.call(this,e,f),(this._gc||this._time===this._duration)&&!this._paused&&this._duration<this.duration())for(n=this,o=n.rawTime()>e._startTime;n._timeline;)o&&n._timeline.smoothChildTiming?n.totalTime(n._totalTime,!0):n._gc&&n._enabled(!0,!1),n=n._timeline;return this},q.remove=function(b){if(b instanceof a){this._remove(b,!1);var c=b._timeline=b.vars.useFrames?a._rootFramesTimeline:a._rootTimeline;return b._startTime=(b._paused?b._pauseTime:c._time)-(b._reversed?b.totalDuration()-b._totalTime:b._totalTime)/b._timeScale,this}if(b instanceof Array||b&&b.push&&i(b)){for(var d=b.length;--d>-1;)this.remove(b[d]);return this}return"string"==typeof b?this.removeLabel(b):this.kill(null,b)},q._remove=function(a,c){b.prototype._remove.call(this,a,c);var d=this._last;return d?this._time>d._startTime+d._totalDuration/d._timeScale&&(this._time=this.duration(),this._totalTime=this._totalDuration):this._time=this._totalTime=this._duration=this._totalDuration=0,this},q.append=function(a,b){return this.add(a,this._parseTimeOrLabel(null,b,!0,a))},q.insert=q.insertMultiple=function(a,b,c,d){return this.add(a,b||0,c,d)},q.appendMultiple=function(a,b,c,d){return this.add(a,this._parseTimeOrLabel(null,b,!0,a),c,d)},q.addLabel=function(a,b){return this._labels[a]=this._parseTimeOrLabel(b),this},q.addPause=function(a,b,d,e){var f=c.delayedCall(0,o,d,e||this);return f.vars.onComplete=f.vars.onReverseComplete=b,f.data="isPause",this._hasPause=!0,this.add(f,a)},q.removeLabel=function(a){return delete this._labels[a],this},q.getLabelTime=function(a){return null!=this._labels[a]?this._labels[a]:-1},q._parseTimeOrLabel=function(b,c,d,e){var f;if(e instanceof a&&e.timeline===this)this.remove(e);else if(e&&(e instanceof Array||e.push&&i(e)))for(f=e.length;--f>-1;)e[f]instanceof a&&e[f].timeline===this&&this.remove(e[f]);if("string"==typeof c)return this._parseTimeOrLabel(c,d&&"number"==typeof b&&null==this._labels[c]?b-this.duration():0,d);if(c=c||0,"string"!=typeof b||!isNaN(b)&&null==this._labels[b])null==b&&(b=this.duration());else{if(f=b.indexOf("="),-1===f)return null==this._labels[b]?d?this._labels[b]=this.duration()+c:c:this._labels[b]+c;c=parseInt(b.charAt(f-1)+"1",10)*Number(b.substr(f+1)),b=f>1?this._parseTimeOrLabel(b.substr(0,f-1),0,d):this.duration()}return Number(b)+c},q.seek=function(a,b){return this.totalTime("number"==typeof a?a:this._parseTimeOrLabel(a),b!==!1)},q.stop=function(){return this.paused(!0)},q.gotoAndPlay=function(a,b){return this.play(a,b)},q.gotoAndStop=function(a,b){return this.pause(a,b)},q.render=function(a,b,c){this._gc&&this._enabled(!0,!1);var d,f,g,h,i,l,m,n=this._dirty?this.totalDuration():this._totalDuration,o=this._time,p=this._startTime,q=this._timeScale,r=this._paused;if(a>=n-1e-7)this._totalTime=this._time=n,this._reversed||this._hasPausedChild()||(f=!0,h="onComplete",i=!!this._timeline.autoRemoveChildren,0===this._duration&&(0>=a&&a>=-1e-7||this._rawPrevTime<0||this._rawPrevTime===e)&&this._rawPrevTime!==a&&this._first&&(i=!0,this._rawPrevTime>e&&(h="onReverseComplete"))),this._rawPrevTime=this._duration||!b||a||this._rawPrevTime===a?a:e,a=n+1e-4;else if(1e-7>a)if(this._totalTime=this._time=0,(0!==o||0===this._duration&&this._rawPrevTime!==e&&(this._rawPrevTime>0||0>a&&this._rawPrevTime>=0))&&(h="onReverseComplete",f=this._reversed),0>a)this._active=!1,this._timeline.autoRemoveChildren&&this._reversed?(i=f=!0,h="onReverseComplete"):this._rawPrevTime>=0&&this._first&&(i=!0),this._rawPrevTime=a;else{if(this._rawPrevTime=this._duration||!b||a||this._rawPrevTime===a?a:e,0===a&&f)for(d=this._first;d&&0===d._startTime;)d._duration||(f=!1),d=d._next;a=0,this._initted||(i=!0)}else{if(this._hasPause&&!this._forcingPlayhead&&!b){if(a>=o)for(d=this._first;d&&d._startTime<=a&&!l;)d._duration||"isPause"!==d.data||d.ratio||0===d._startTime&&0===this._rawPrevTime||(l=d),d=d._next;else for(d=this._last;d&&d._startTime>=a&&!l;)d._duration||"isPause"===d.data&&d._rawPrevTime>0&&(l=d),d=d._prev;l&&(this._time=a=l._startTime,this._totalTime=a+this._cycle*(this._totalDuration+this._repeatDelay))}this._totalTime=this._time=this._rawPrevTime=a}if(this._time!==o&&this._first||c||i||l){if(this._initted||(this._initted=!0),this._active||!this._paused&&this._time!==o&&a>0&&(this._active=!0),0===o&&this.vars.onStart&&(0===this._time&&this._duration||b||this._callback("onStart")),m=this._time,m>=o)for(d=this._first;d&&(g=d._next,m===this._time&&(!this._paused||r));)(d._active||d._startTime<=m&&!d._paused&&!d._gc)&&(l===d&&this.pause(),d._reversed?d.render((d._dirty?d.totalDuration():d._totalDuration)-(a-d._startTime)*d._timeScale,b,c):d.render((a-d._startTime)*d._timeScale,b,c)),d=g;else for(d=this._last;d&&(g=d._prev,m===this._time&&(!this._paused||r));){if(d._active||d._startTime<=o&&!d._paused&&!d._gc){if(l===d){for(l=d._prev;l&&l.endTime()>this._time;)l.render(l._reversed?l.totalDuration()-(a-l._startTime)*l._timeScale:(a-l._startTime)*l._timeScale,b,c),l=l._prev;l=null,this.pause()}d._reversed?d.render((d._dirty?d.totalDuration():d._totalDuration)-(a-d._startTime)*d._timeScale,b,c):d.render((a-d._startTime)*d._timeScale,b,c)}d=g}this._onUpdate&&(b||(j.length&&k(),this._callback("onUpdate"))),h&&(this._gc||(p===this._startTime||q!==this._timeScale)&&(0===this._time||n>=this.totalDuration())&&(f&&(j.length&&k(),this._timeline.autoRemoveChildren&&this._enabled(!1,!1),this._active=!1),!b&&this.vars[h]&&this._callback(h)))}},q._hasPausedChild=function(){for(var a=this._first;a;){if(a._paused||a instanceof d&&a._hasPausedChild())return!0;a=a._next}return!1},q.getChildren=function(a,b,d,e){e=e||-9999999999;for(var f=[],g=this._first,h=0;g;)g._startTime<e||(g instanceof c?b!==!1&&(f[h++]=g):(d!==!1&&(f[h++]=g),a!==!1&&(f=f.concat(g.getChildren(!0,b,d)),h=f.length))),g=g._next;return f},q.getTweensOf=function(a,b){var d,e,f=this._gc,g=[],h=0;for(f&&this._enabled(!0,!0),d=c.getTweensOf(a),e=d.length;--e>-1;)(d[e].timeline===this||b&&this._contains(d[e]))&&(g[h++]=d[e]);return f&&this._enabled(!1,!0),g},q.recent=function(){return this._recent},q._contains=function(a){for(var b=a.timeline;b;){if(b===this)return!0;b=b.timeline}return!1},q.shiftChildren=function(a,b,c){c=c||0;for(var d,e=this._first,f=this._labels;e;)e._startTime>=c&&(e._startTime+=a),e=e._next;if(b)for(d in f)f[d]>=c&&(f[d]+=a);return this._uncache(!0)},q._kill=function(a,b){if(!a&&!b)return this._enabled(!1,!1);for(var c=b?this.getTweensOf(b):this.getChildren(!0,!0,!1),d=c.length,e=!1;--d>-1;)c[d]._kill(a,b)&&(e=!0);return e},q.clear=function(a){var b=this.getChildren(!1,!0,!0),c=b.length;for(this._time=this._totalTime=0;--c>-1;)b[c]._enabled(!1,!1);return a!==!1&&(this._labels={}),this._uncache(!0)},q.invalidate=function(){for(var b=this._first;b;)b.invalidate(),b=b._next;return a.prototype.invalidate.call(this)},q._enabled=function(a,c){if(a===this._gc)for(var d=this._first;d;)d._enabled(a,!0),d=d._next;return b.prototype._enabled.call(this,a,c)},q.totalTime=function(b,c,d){this._forcingPlayhead=!0;var e=a.prototype.totalTime.apply(this,arguments);return this._forcingPlayhead=!1,e},q.duration=function(a){return arguments.length?(0!==this.duration()&&0!==a&&this.timeScale(this._duration/a),this):(this._dirty&&this.totalDuration(),this._duration)},q.totalDuration=function(a){if(!arguments.length){if(this._dirty){for(var b,c,d=0,e=this._last,f=999999999999;e;)b=e._prev,e._dirty&&e.totalDuration(),e._startTime>f&&this._sortChildren&&!e._paused?this.add(e,e._startTime-e._delay):f=e._startTime,e._startTime<0&&!e._paused&&(d-=e._startTime,this._timeline.smoothChildTiming&&(this._startTime+=e._startTime/this._timeScale),this.shiftChildren(-e._startTime,!1,-9999999999),f=0),c=e._startTime+e._totalDuration/e._timeScale,c>d&&(d=c),e=b;this._duration=this._totalDuration=d,this._dirty=!1}return this._totalDuration}return a&&this.totalDuration()?this.timeScale(this._totalDuration/a):this},q.paused=function(b){if(!b)for(var c=this._first,d=this._time;c;)c._startTime===d&&"isPause"===c.data&&(c._rawPrevTime=0),c=c._next;return a.prototype.paused.apply(this,arguments)},q.usesFrames=function(){for(var b=this._timeline;b._timeline;)b=b._timeline;return b===a._rootFramesTimeline},q.rawTime=function(){return this._paused?this._totalTime:(this._timeline.rawTime()-this._startTime)*this._timeScale},d},!0),_gsScope._gsDefine("TimelineMax",["TimelineLite","TweenLite","easing.Ease"],function(a,b,c){var d=function(b){a.call(this,b),this._repeat=this.vars.repeat||0,this._repeatDelay=this.vars.repeatDelay||0,this._cycle=0,this._yoyo=this.vars.yoyo===!0,this._dirty=!0},e=1e-10,f=b._internals,g=f.lazyTweens,h=f.lazyRender,i=_gsScope._gsDefine.globals,j=new c(null,null,1,0),k=d.prototype=new a;return k.constructor=d,k.kill()._gc=!1,d.version="1.19.0",k.invalidate=function(){return this._yoyo=this.vars.yoyo===!0,this._repeat=this.vars.repeat||0,this._repeatDelay=this.vars.repeatDelay||0,this._uncache(!0),a.prototype.invalidate.call(this)},k.addCallback=function(a,c,d,e){return this.add(b.delayedCall(0,a,d,e),c)},k.removeCallback=function(a,b){if(a)if(null==b)this._kill(null,a);else for(var c=this.getTweensOf(a,!1),d=c.length,e=this._parseTimeOrLabel(b);--d>-1;)c[d]._startTime===e&&c[d]._enabled(!1,!1);return this},k.removePause=function(b){return this.removeCallback(a._internals.pauseCallback,b)},k.tweenTo=function(a,c){c=c||{};var d,e,f,g={ease:j,useFrames:this.usesFrames(),immediateRender:!1},h=c.repeat&&i.TweenMax||b;for(e in c)g[e]=c[e];return g.time=this._parseTimeOrLabel(a),d=Math.abs(Number(g.time)-this._time)/this._timeScale||.001,f=new h(this,d,g),g.onStart=function(){f.target.paused(!0),f.vars.time!==f.target.time()&&d===f.duration()&&f.duration(Math.abs(f.vars.time-f.target.time())/f.target._timeScale),c.onStart&&f._callback("onStart")},f},k.tweenFromTo=function(a,b,c){c=c||{},a=this._parseTimeOrLabel(a),c.startAt={onComplete:this.seek,onCompleteParams:[a],callbackScope:this},c.immediateRender=c.immediateRender!==!1;var d=this.tweenTo(b,c);return d.duration(Math.abs(d.vars.time-a)/this._timeScale||.001)},k.render=function(a,b,c){this._gc&&this._enabled(!0,!1);var d,f,i,j,k,l,m,n,o=this._dirty?this.totalDuration():this._totalDuration,p=this._duration,q=this._time,r=this._totalTime,s=this._startTime,t=this._timeScale,u=this._rawPrevTime,v=this._paused,w=this._cycle;if(a>=o-1e-7)this._locked||(this._totalTime=o,this._cycle=this._repeat),this._reversed||this._hasPausedChild()||(f=!0,j="onComplete",k=!!this._timeline.autoRemoveChildren,0===this._duration&&(0>=a&&a>=-1e-7||0>u||u===e)&&u!==a&&this._first&&(k=!0,u>e&&(j="onReverseComplete"))),this._rawPrevTime=this._duration||!b||a||this._rawPrevTime===a?a:e,this._yoyo&&0!==(1&this._cycle)?this._time=a=0:(this._time=p,a=p+1e-4);else if(1e-7>a)if(this._locked||(this._totalTime=this._cycle=0),this._time=0,(0!==q||0===p&&u!==e&&(u>0||0>a&&u>=0)&&!this._locked)&&(j="onReverseComplete",f=this._reversed),0>a)this._active=!1,this._timeline.autoRemoveChildren&&this._reversed?(k=f=!0,j="onReverseComplete"):u>=0&&this._first&&(k=!0),this._rawPrevTime=a;else{if(this._rawPrevTime=p||!b||a||this._rawPrevTime===a?a:e,0===a&&f)for(d=this._first;d&&0===d._startTime;)d._duration||(f=!1),d=d._next;a=0,this._initted||(k=!0)}else if(0===p&&0>u&&(k=!0),this._time=this._rawPrevTime=a,this._locked||(this._totalTime=a,0!==this._repeat&&(l=p+this._repeatDelay,this._cycle=this._totalTime/l>>0,0!==this._cycle&&this._cycle===this._totalTime/l&&a>=r&&this._cycle--,this._time=this._totalTime-this._cycle*l,this._yoyo&&0!==(1&this._cycle)&&(this._time=p-this._time),this._time>p?(this._time=p,a=p+1e-4):this._time<0?this._time=a=0:a=this._time)),this._hasPause&&!this._forcingPlayhead&&!b){if(a=this._time,a>=q)for(d=this._first;d&&d._startTime<=a&&!m;)d._duration||"isPause"!==d.data||d.ratio||0===d._startTime&&0===this._rawPrevTime||(m=d),d=d._next;else for(d=this._last;d&&d._startTime>=a&&!m;)d._duration||"isPause"===d.data&&d._rawPrevTime>0&&(m=d),d=d._prev;m&&(this._time=a=m._startTime,this._totalTime=a+this._cycle*(this._totalDuration+this._repeatDelay))}if(this._cycle!==w&&!this._locked){var x=this._yoyo&&0!==(1&w),y=x===(this._yoyo&&0!==(1&this._cycle)),z=this._totalTime,A=this._cycle,B=this._rawPrevTime,C=this._time;if(this._totalTime=w*p,this._cycle<w?x=!x:this._totalTime+=p,this._time=q,this._rawPrevTime=0===p?u-1e-4:u,this._cycle=w,this._locked=!0,q=x?0:p,this.render(q,b,0===p),b||this._gc||this.vars.onRepeat&&this._callback("onRepeat"),q!==this._time)return;if(y&&(q=x?p+1e-4:-1e-4,this.render(q,!0,!1)),this._locked=!1,this._paused&&!v)return;this._time=C,this._totalTime=z,this._cycle=A,this._rawPrevTime=B}if(!(this._time!==q&&this._first||c||k||m))return void(r!==this._totalTime&&this._onUpdate&&(b||this._callback("onUpdate")));if(this._initted||(this._initted=!0),this._active||!this._paused&&this._totalTime!==r&&a>0&&(this._active=!0),0===r&&this.vars.onStart&&(0===this._totalTime&&this._totalDuration||b||this._callback("onStart")),n=this._time,n>=q)for(d=this._first;d&&(i=d._next,n===this._time&&(!this._paused||v));)(d._active||d._startTime<=this._time&&!d._paused&&!d._gc)&&(m===d&&this.pause(),d._reversed?d.render((d._dirty?d.totalDuration():d._totalDuration)-(a-d._startTime)*d._timeScale,b,c):d.render((a-d._startTime)*d._timeScale,b,c)),d=i;else for(d=this._last;d&&(i=d._prev,n===this._time&&(!this._paused||v));){if(d._active||d._startTime<=q&&!d._paused&&!d._gc){if(m===d){for(m=d._prev;m&&m.endTime()>this._time;)m.render(m._reversed?m.totalDuration()-(a-m._startTime)*m._timeScale:(a-m._startTime)*m._timeScale,b,c),m=m._prev;m=null,this.pause()}d._reversed?d.render((d._dirty?d.totalDuration():d._totalDuration)-(a-d._startTime)*d._timeScale,b,c):d.render((a-d._startTime)*d._timeScale,b,c)}d=i}this._onUpdate&&(b||(g.length&&h(),this._callback("onUpdate"))),j&&(this._locked||this._gc||(s===this._startTime||t!==this._timeScale)&&(0===this._time||o>=this.totalDuration())&&(f&&(g.length&&h(),this._timeline.autoRemoveChildren&&this._enabled(!1,!1),this._active=!1),!b&&this.vars[j]&&this._callback(j)))},k.getActive=function(a,b,c){null==a&&(a=!0),null==b&&(b=!0),null==c&&(c=!1);var d,e,f=[],g=this.getChildren(a,b,c),h=0,i=g.length;for(d=0;i>d;d++)e=g[d],e.isActive()&&(f[h++]=e);return f},k.getLabelAfter=function(a){a||0!==a&&(a=this._time);var b,c=this.getLabelsArray(),d=c.length;for(b=0;d>b;b++)if(c[b].time>a)return c[b].name;return null},k.getLabelBefore=function(a){null==a&&(a=this._time);for(var b=this.getLabelsArray(),c=b.length;--c>-1;)if(b[c].time<a)return b[c].name;return null},k.getLabelsArray=function(){var a,b=[],c=0;for(a in this._labels)b[c++]={time:this._labels[a],name:a};return b.sort(function(a,b){return a.time-b.time}),b},k.progress=function(a,b){return arguments.length?this.totalTime(this.duration()*(this._yoyo&&0!==(1&this._cycle)?1-a:a)+this._cycle*(this._duration+this._repeatDelay),b):this._time/this.duration()},k.totalProgress=function(a,b){return arguments.length?this.totalTime(this.totalDuration()*a,b):this._totalTime/this.totalDuration()},k.totalDuration=function(b){return arguments.length?-1!==this._repeat&&b?this.timeScale(this.totalDuration()/b):this:(this._dirty&&(a.prototype.totalDuration.call(this),this._totalDuration=-1===this._repeat?999999999999:this._duration*(this._repeat+1)+this._repeatDelay*this._repeat),this._totalDuration)},k.time=function(a,b){return arguments.length?(this._dirty&&this.totalDuration(),a>this._duration&&(a=this._duration),this._yoyo&&0!==(1&this._cycle)?a=this._duration-a+this._cycle*(this._duration+this._repeatDelay):0!==this._repeat&&(a+=this._cycle*(this._duration+this._repeatDelay)),this.totalTime(a,b)):this._time},k.repeat=function(a){return arguments.length?(this._repeat=a,this._uncache(!0)):this._repeat},k.repeatDelay=function(a){return arguments.length?(this._repeatDelay=a,this._uncache(!0)):this._repeatDelay},k.yoyo=function(a){return arguments.length?(this._yoyo=a,this):this._yoyo},k.currentLabel=function(a){return arguments.length?this.seek(a,!0):this.getLabelBefore(this._time+1e-8)},d},!0),function(){var a=180/Math.PI,b=[],c=[],d=[],e={},f=_gsScope._gsDefine.globals,g=function(a,b,c,d){c===d&&(c=d-(d-b)/1e6),a===b&&(b=a+(c-a)/1e6),this.a=a,this.b=b,this.c=c,this.d=d,this.da=d-a,this.ca=c-a,this.ba=b-a},h=",x,y,z,left,top,right,bottom,marginTop,marginLeft,marginRight,marginBottom,paddingLeft,paddingTop,paddingRight,paddingBottom,backgroundPosition,backgroundPosition_y,",i=function(a,b,c,d){var e={a:a},f={},g={},h={c:d},i=(a+b)/2,j=(b+c)/2,k=(c+d)/2,l=(i+j)/2,m=(j+k)/2,n=(m-l)/8;return e.b=i+(a-i)/4,f.b=l+n,e.c=f.a=(e.b+f.b)/2,f.c=g.a=(l+m)/2,g.b=m-n,h.b=k+(d-k)/4,g.c=h.a=(g.b+h.b)/2,[e,f,g,h]},j=function(a,e,f,g,h){var j,k,l,m,n,o,p,q,r,s,t,u,v,w=a.length-1,x=0,y=a[0].a;for(j=0;w>j;j++)n=a[x],k=n.a,l=n.d,m=a[x+1].d,h?(t=b[j],u=c[j],v=(u+t)*e*.25/(g?.5:d[j]||.5),o=l-(l-k)*(g?.5*e:0!==t?v/t:0),p=l+(m-l)*(g?.5*e:0!==u?v/u:0),q=l-(o+((p-o)*(3*t/(t+u)+.5)/4||0))):(o=l-(l-k)*e*.5,p=l+(m-l)*e*.5,q=l-(o+p)/2),o+=q,p+=q,n.c=r=o,0!==j?n.b=y:n.b=y=n.a+.6*(n.c-n.a),n.da=l-k,n.ca=r-k,n.ba=y-k,f?(s=i(k,y,r,l),a.splice(x,1,s[0],s[1],s[2],s[3]),x+=4):x++,y=p;n=a[x],n.b=y,n.c=y+.4*(n.d-y),n.da=n.d-n.a,n.ca=n.c-n.a,n.ba=y-n.a,f&&(s=i(n.a,y,n.c,n.d),a.splice(x,1,s[0],s[1],s[2],s[3]))},k=function(a,d,e,f){var h,i,j,k,l,m,n=[];if(f)for(a=[f].concat(a),i=a.length;--i>-1;)"string"==typeof(m=a[i][d])&&"="===m.charAt(1)&&(a[i][d]=f[d]+Number(m.charAt(0)+m.substr(2)));if(h=a.length-2,0>h)return n[0]=new g(a[0][d],0,0,a[-1>h?0:1][d]),n;for(i=0;h>i;i++)j=a[i][d],k=a[i+1][d],n[i]=new g(j,0,0,k),e&&(l=a[i+2][d],b[i]=(b[i]||0)+(k-j)*(k-j),c[i]=(c[i]||0)+(l-k)*(l-k));return n[i]=new g(a[i][d],0,0,a[i+1][d]),n},l=function(a,f,g,i,l,m){var n,o,p,q,r,s,t,u,v={},w=[],x=m||a[0];l="string"==typeof l?","+l+",":h,null==f&&(f=1);for(o in a[0])w.push(o);if(a.length>1){for(u=a[a.length-1],t=!0,n=w.length;--n>-1;)if(o=w[n],Math.abs(x[o]-u[o])>.05){t=!1;break}t&&(a=a.concat(),m&&a.unshift(m),a.push(a[1]),m=a[a.length-3])}for(b.length=c.length=d.length=0,n=w.length;--n>-1;)o=w[n],e[o]=-1!==l.indexOf(","+o+","),v[o]=k(a,o,e[o],m);for(n=b.length;--n>-1;)b[n]=Math.sqrt(b[n]),c[n]=Math.sqrt(c[n]);if(!i){for(n=w.length;--n>-1;)if(e[o])for(p=v[w[n]],s=p.length-1,q=0;s>q;q++)r=p[q+1].da/c[q]+p[q].da/b[q]||0,d[q]=(d[q]||0)+r*r;for(n=d.length;--n>-1;)d[n]=Math.sqrt(d[n])}for(n=w.length,q=g?4:1;--n>-1;)o=w[n],p=v[o],j(p,f,g,i,e[o]),t&&(p.splice(0,q),p.splice(p.length-q,q));return v},m=function(a,b,c){b=b||"soft";var d,e,f,h,i,j,k,l,m,n,o,p={},q="cubic"===b?3:2,r="soft"===b,s=[];if(r&&c&&(a=[c].concat(a)),null==a||a.length<q+1)throw"invalid Bezier data";for(m in a[0])s.push(m);for(j=s.length;--j>-1;){for(m=s[j],p[m]=i=[],n=0,l=a.length,k=0;l>k;k++)d=null==c?a[k][m]:"string"==typeof(o=a[k][m])&&"="===o.charAt(1)?c[m]+Number(o.charAt(0)+o.substr(2)):Number(o),r&&k>1&&l-1>k&&(i[n++]=(d+i[n-2])/2),i[n++]=d;for(l=n-q+1,n=0,k=0;l>k;k+=q)d=i[k],e=i[k+1],f=i[k+2],h=2===q?0:i[k+3],i[n++]=o=3===q?new g(d,e,f,h):new g(d,(2*e+d)/3,(2*e+f)/3,f);i.length=n}return p},n=function(a,b,c){for(var d,e,f,g,h,i,j,k,l,m,n,o=1/c,p=a.length;--p>-1;)for(m=a[p],f=m.a,g=m.d-f,h=m.c-f,i=m.b-f,d=e=0,k=1;c>=k;k++)j=o*k,l=1-j,d=e-(e=(j*j*g+3*l*(j*h+l*i))*j),n=p*c+k-1,b[n]=(b[n]||0)+d*d},o=function(a,b){b=b>>0||6;var c,d,e,f,g=[],h=[],i=0,j=0,k=b-1,l=[],m=[];for(c in a)n(a[c],g,b);for(e=g.length,d=0;e>d;d++)i+=Math.sqrt(g[d]),f=d%b,m[f]=i,f===k&&(j+=i,f=d/b>>0,l[f]=m,h[f]=j,i=0,m=[]);return{length:j,lengths:h,
segments:l}},p=_gsScope._gsDefine.plugin({propName:"bezier",priority:-1,version:"1.3.7",API:2,global:!0,init:function(a,b,c){this._target=a,b instanceof Array&&(b={values:b}),this._func={},this._mod={},this._props=[],this._timeRes=null==b.timeResolution?6:parseInt(b.timeResolution,10);var d,e,f,g,h,i=b.values||[],j={},k=i[0],n=b.autoRotate||c.vars.orientToBezier;this._autoRotate=n?n instanceof Array?n:[["x","y","rotation",n===!0?0:Number(n)||0]]:null;for(d in k)this._props.push(d);for(f=this._props.length;--f>-1;)d=this._props[f],this._overwriteProps.push(d),e=this._func[d]="function"==typeof a[d],j[d]=e?a[d.indexOf("set")||"function"!=typeof a["get"+d.substr(3)]?d:"get"+d.substr(3)]():parseFloat(a[d]),h||j[d]!==i[0][d]&&(h=j);if(this._beziers="cubic"!==b.type&&"quadratic"!==b.type&&"soft"!==b.type?l(i,isNaN(b.curviness)?1:b.curviness,!1,"thruBasic"===b.type,b.correlate,h):m(i,b.type,j),this._segCount=this._beziers[d].length,this._timeRes){var p=o(this._beziers,this._timeRes);this._length=p.length,this._lengths=p.lengths,this._segments=p.segments,this._l1=this._li=this._s1=this._si=0,this._l2=this._lengths[0],this._curSeg=this._segments[0],this._s2=this._curSeg[0],this._prec=1/this._curSeg.length}if(n=this._autoRotate)for(this._initialRotations=[],n[0]instanceof Array||(this._autoRotate=n=[n]),f=n.length;--f>-1;){for(g=0;3>g;g++)d=n[f][g],this._func[d]="function"==typeof a[d]?a[d.indexOf("set")||"function"!=typeof a["get"+d.substr(3)]?d:"get"+d.substr(3)]:!1;d=n[f][2],this._initialRotations[f]=(this._func[d]?this._func[d].call(this._target):this._target[d])||0,this._overwriteProps.push(d)}return this._startRatio=c.vars.runBackwards?1:0,!0},set:function(b){var c,d,e,f,g,h,i,j,k,l,m=this._segCount,n=this._func,o=this._target,p=b!==this._startRatio;if(this._timeRes){if(k=this._lengths,l=this._curSeg,b*=this._length,e=this._li,b>this._l2&&m-1>e){for(j=m-1;j>e&&(this._l2=k[++e])<=b;);this._l1=k[e-1],this._li=e,this._curSeg=l=this._segments[e],this._s2=l[this._s1=this._si=0]}else if(b<this._l1&&e>0){for(;e>0&&(this._l1=k[--e])>=b;);0===e&&b<this._l1?this._l1=0:e++,this._l2=k[e],this._li=e,this._curSeg=l=this._segments[e],this._s1=l[(this._si=l.length-1)-1]||0,this._s2=l[this._si]}if(c=e,b-=this._l1,e=this._si,b>this._s2&&e<l.length-1){for(j=l.length-1;j>e&&(this._s2=l[++e])<=b;);this._s1=l[e-1],this._si=e}else if(b<this._s1&&e>0){for(;e>0&&(this._s1=l[--e])>=b;);0===e&&b<this._s1?this._s1=0:e++,this._s2=l[e],this._si=e}h=(e+(b-this._s1)/(this._s2-this._s1))*this._prec||0}else c=0>b?0:b>=1?m-1:m*b>>0,h=(b-c*(1/m))*m;for(d=1-h,e=this._props.length;--e>-1;)f=this._props[e],g=this._beziers[f][c],i=(h*h*g.da+3*d*(h*g.ca+d*g.ba))*h+g.a,this._mod[f]&&(i=this._mod[f](i,o)),n[f]?o[f](i):o[f]=i;if(this._autoRotate){var q,r,s,t,u,v,w,x=this._autoRotate;for(e=x.length;--e>-1;)f=x[e][2],v=x[e][3]||0,w=x[e][4]===!0?1:a,g=this._beziers[x[e][0]],q=this._beziers[x[e][1]],g&&q&&(g=g[c],q=q[c],r=g.a+(g.b-g.a)*h,t=g.b+(g.c-g.b)*h,r+=(t-r)*h,t+=(g.c+(g.d-g.c)*h-t)*h,s=q.a+(q.b-q.a)*h,u=q.b+(q.c-q.b)*h,s+=(u-s)*h,u+=(q.c+(q.d-q.c)*h-u)*h,i=p?Math.atan2(u-s,t-r)*w+v:this._initialRotations[e],this._mod[f]&&(i=this._mod[f](i,o)),n[f]?o[f](i):o[f]=i)}}}),q=p.prototype;p.bezierThrough=l,p.cubicToQuadratic=i,p._autoCSS=!0,p.quadraticToCubic=function(a,b,c){return new g(a,(2*b+a)/3,(2*b+c)/3,c)},p._cssRegister=function(){var a=f.CSSPlugin;if(a){var b=a._internals,c=b._parseToProxy,d=b._setPluginRatio,e=b.CSSPropTween;b._registerComplexSpecialProp("bezier",{parser:function(a,b,f,g,h,i){b instanceof Array&&(b={values:b}),i=new p;var j,k,l,m=b.values,n=m.length-1,o=[],q={};if(0>n)return h;for(j=0;n>=j;j++)l=c(a,m[j],g,h,i,n!==j),o[j]=l.end;for(k in b)q[k]=b[k];return q.values=o,h=new e(a,"bezier",0,0,l.pt,2),h.data=l,h.plugin=i,h.setRatio=d,0===q.autoRotate&&(q.autoRotate=!0),!q.autoRotate||q.autoRotate instanceof Array||(j=q.autoRotate===!0?0:Number(q.autoRotate),q.autoRotate=null!=l.end.left?[["left","top","rotation",j,!1]]:null!=l.end.x?[["x","y","rotation",j,!1]]:!1),q.autoRotate&&(g._transform||g._enableTransforms(!1),l.autoRotate=g._target._gsTransform,l.proxy.rotation=l.autoRotate.rotation||0,g._overwriteProps.push("rotation")),i._onInitTween(l.proxy,q,g._tween),h}})}},q._mod=function(a){for(var b,c=this._overwriteProps,d=c.length;--d>-1;)b=a[c[d]],b&&"function"==typeof b&&(this._mod[c[d]]=b)},q._kill=function(a){var b,c,d=this._props;for(b in this._beziers)if(b in a)for(delete this._beziers[b],delete this._func[b],c=d.length;--c>-1;)d[c]===b&&d.splice(c,1);if(d=this._autoRotate)for(c=d.length;--c>-1;)a[d[c][2]]&&d.splice(c,1);return this._super._kill.call(this,a)}}(),_gsScope._gsDefine("plugins.CSSPlugin",["plugins.TweenPlugin","TweenLite"],function(a,b){var c,d,e,f,g=function(){a.call(this,"css"),this._overwriteProps.length=0,this.setRatio=g.prototype.setRatio},h=_gsScope._gsDefine.globals,i={},j=g.prototype=new a("css");j.constructor=g,g.version="1.19.0",g.API=2,g.defaultTransformPerspective=0,g.defaultSkewType="compensated",g.defaultSmoothOrigin=!0,j="px",g.suffixMap={top:j,right:j,bottom:j,left:j,width:j,height:j,fontSize:j,padding:j,margin:j,perspective:j,lineHeight:""};var k,l,m,n,o,p,q,r,s=/(?:\-|\.|\b)(\d|\.|e\-)+/g,t=/(?:\d|\-\d|\.\d|\-\.\d|\+=\d|\-=\d|\+=.\d|\-=\.\d)+/g,u=/(?:\+=|\-=|\-|\b)[\d\-\.]+[a-zA-Z0-9]*(?:%|\b)/gi,v=/(?![+-]?\d*\.?\d+|[+-]|e[+-]\d+)[^0-9]/g,w=/(?:\d|\-|\+|=|#|\.)*/g,x=/opacity *= *([^)]*)/i,y=/opacity:([^;]*)/i,z=/alpha\(opacity *=.+?\)/i,A=/^(rgb|hsl)/,B=/([A-Z])/g,C=/-([a-z])/gi,D=/(^(?:url\(\"|url\())|(?:(\"\))$|\)$)/gi,E=function(a,b){return b.toUpperCase()},F=/(?:Left|Right|Width)/i,G=/(M11|M12|M21|M22)=[\d\-\.e]+/gi,H=/progid\:DXImageTransform\.Microsoft\.Matrix\(.+?\)/i,I=/,(?=[^\)]*(?:\(|$))/gi,J=/[\s,\(]/i,K=Math.PI/180,L=180/Math.PI,M={},N=document,O=function(a){return N.createElementNS?N.createElementNS("http://www.w3.org/1999/xhtml",a):N.createElement(a)},P=O("div"),Q=O("img"),R=g._internals={_specialProps:i},S=navigator.userAgent,T=function(){var a=S.indexOf("Android"),b=O("a");return m=-1!==S.indexOf("Safari")&&-1===S.indexOf("Chrome")&&(-1===a||Number(S.substr(a+8,1))>3),o=m&&Number(S.substr(S.indexOf("Version/")+8,1))<6,n=-1!==S.indexOf("Firefox"),(/MSIE ([0-9]{1,}[\.0-9]{0,})/.exec(S)||/Trident\/.*rv:([0-9]{1,}[\.0-9]{0,})/.exec(S))&&(p=parseFloat(RegExp.$1)),b?(b.style.cssText="top:1px;opacity:.55;",/^0.55/.test(b.style.opacity)):!1}(),U=function(a){return x.test("string"==typeof a?a:(a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100:1},V=function(a){window.console&&console.log(a)},W="",X="",Y=function(a,b){b=b||P;var c,d,e=b.style;if(void 0!==e[a])return a;for(a=a.charAt(0).toUpperCase()+a.substr(1),c=["O","Moz","ms","Ms","Webkit"],d=5;--d>-1&&void 0===e[c[d]+a];);return d>=0?(X=3===d?"ms":c[d],W="-"+X.toLowerCase()+"-",X+a):null},Z=N.defaultView?N.defaultView.getComputedStyle:function(){},$=g.getStyle=function(a,b,c,d,e){var f;return T||"opacity"!==b?(!d&&a.style[b]?f=a.style[b]:(c=c||Z(a))?f=c[b]||c.getPropertyValue(b)||c.getPropertyValue(b.replace(B,"-$1").toLowerCase()):a.currentStyle&&(f=a.currentStyle[b]),null==e||f&&"none"!==f&&"auto"!==f&&"auto auto"!==f?f:e):U(a)},_=R.convertToPixels=function(a,c,d,e,f){if("px"===e||!e)return d;if("auto"===e||!d)return 0;var h,i,j,k=F.test(c),l=a,m=P.style,n=0>d,o=1===d;if(n&&(d=-d),o&&(d*=100),"%"===e&&-1!==c.indexOf("border"))h=d/100*(k?a.clientWidth:a.clientHeight);else{if(m.cssText="border:0 solid red;position:"+$(a,"position")+";line-height:0;","%"!==e&&l.appendChild&&"v"!==e.charAt(0)&&"rem"!==e)m[k?"borderLeftWidth":"borderTopWidth"]=d+e;else{if(l=a.parentNode||N.body,i=l._gsCache,j=b.ticker.frame,i&&k&&i.time===j)return i.width*d/100;m[k?"width":"height"]=d+e}l.appendChild(P),h=parseFloat(P[k?"offsetWidth":"offsetHeight"]),l.removeChild(P),k&&"%"===e&&g.cacheWidths!==!1&&(i=l._gsCache=l._gsCache||{},i.time=j,i.width=h/d*100),0!==h||f||(h=_(a,c,d,e,!0))}return o&&(h/=100),n?-h:h},aa=R.calculateOffset=function(a,b,c){if("absolute"!==$(a,"position",c))return 0;var d="left"===b?"Left":"Top",e=$(a,"margin"+d,c);return a["offset"+d]-(_(a,b,parseFloat(e),e.replace(w,""))||0)},ba=function(a,b){var c,d,e,f={};if(b=b||Z(a,null))if(c=b.length)for(;--c>-1;)e=b[c],(-1===e.indexOf("-transform")||Ca===e)&&(f[e.replace(C,E)]=b.getPropertyValue(e));else for(c in b)(-1===c.indexOf("Transform")||Ba===c)&&(f[c]=b[c]);else if(b=a.currentStyle||a.style)for(c in b)"string"==typeof c&&void 0===f[c]&&(f[c.replace(C,E)]=b[c]);return T||(f.opacity=U(a)),d=Pa(a,b,!1),f.rotation=d.rotation,f.skewX=d.skewX,f.scaleX=d.scaleX,f.scaleY=d.scaleY,f.x=d.x,f.y=d.y,Ea&&(f.z=d.z,f.rotationX=d.rotationX,f.rotationY=d.rotationY,f.scaleZ=d.scaleZ),f.filters&&delete f.filters,f},ca=function(a,b,c,d,e){var f,g,h,i={},j=a.style;for(g in c)"cssText"!==g&&"length"!==g&&isNaN(g)&&(b[g]!==(f=c[g])||e&&e[g])&&-1===g.indexOf("Origin")&&("number"==typeof f||"string"==typeof f)&&(i[g]="auto"!==f||"left"!==g&&"top"!==g?""!==f&&"auto"!==f&&"none"!==f||"string"!=typeof b[g]||""===b[g].replace(v,"")?f:0:aa(a,g),void 0!==j[g]&&(h=new ra(j,g,j[g],h)));if(d)for(g in d)"className"!==g&&(i[g]=d[g]);return{difs:i,firstMPT:h}},da={width:["Left","Right"],height:["Top","Bottom"]},ea=["marginLeft","marginRight","marginTop","marginBottom"],fa=function(a,b,c){if("svg"===(a.nodeName+"").toLowerCase())return(c||Z(a))[b]||0;if(a.getBBox&&Ma(a))return a.getBBox()[b]||0;var d=parseFloat("width"===b?a.offsetWidth:a.offsetHeight),e=da[b],f=e.length;for(c=c||Z(a,null);--f>-1;)d-=parseFloat($(a,"padding"+e[f],c,!0))||0,d-=parseFloat($(a,"border"+e[f]+"Width",c,!0))||0;return d},ga=function(a,b){if("contain"===a||"auto"===a||"auto auto"===a)return a+" ";(null==a||""===a)&&(a="0 0");var c,d=a.split(" "),e=-1!==a.indexOf("left")?"0%":-1!==a.indexOf("right")?"100%":d[0],f=-1!==a.indexOf("top")?"0%":-1!==a.indexOf("bottom")?"100%":d[1];if(d.length>3&&!b){for(d=a.split(", ").join(",").split(","),a=[],c=0;c<d.length;c++)a.push(ga(d[c]));return a.join(",")}return null==f?f="center"===e?"50%":"0":"center"===f&&(f="50%"),("center"===e||isNaN(parseFloat(e))&&-1===(e+"").indexOf("="))&&(e="50%"),a=e+" "+f+(d.length>2?" "+d[2]:""),b&&(b.oxp=-1!==e.indexOf("%"),b.oyp=-1!==f.indexOf("%"),b.oxr="="===e.charAt(1),b.oyr="="===f.charAt(1),b.ox=parseFloat(e.replace(v,"")),b.oy=parseFloat(f.replace(v,"")),b.v=a),b||a},ha=function(a,b){return"function"==typeof a&&(a=a(r,q)),"string"==typeof a&&"="===a.charAt(1)?parseInt(a.charAt(0)+"1",10)*parseFloat(a.substr(2)):parseFloat(a)-parseFloat(b)||0},ia=function(a,b){return"function"==typeof a&&(a=a(r,q)),null==a?b:"string"==typeof a&&"="===a.charAt(1)?parseInt(a.charAt(0)+"1",10)*parseFloat(a.substr(2))+b:parseFloat(a)||0},ja=function(a,b,c,d){var e,f,g,h,i,j=1e-6;return"function"==typeof a&&(a=a(r,q)),null==a?h=b:"number"==typeof a?h=a:(e=360,f=a.split("_"),i="="===a.charAt(1),g=(i?parseInt(a.charAt(0)+"1",10)*parseFloat(f[0].substr(2)):parseFloat(f[0]))*(-1===a.indexOf("rad")?1:L)-(i?0:b),f.length&&(d&&(d[c]=b+g),-1!==a.indexOf("short")&&(g%=e,g!==g%(e/2)&&(g=0>g?g+e:g-e)),-1!==a.indexOf("_cw")&&0>g?g=(g+9999999999*e)%e-(g/e|0)*e:-1!==a.indexOf("ccw")&&g>0&&(g=(g-9999999999*e)%e-(g/e|0)*e)),h=b+g),j>h&&h>-j&&(h=0),h},ka={aqua:[0,255,255],lime:[0,255,0],silver:[192,192,192],black:[0,0,0],maroon:[128,0,0],teal:[0,128,128],blue:[0,0,255],navy:[0,0,128],white:[255,255,255],fuchsia:[255,0,255],olive:[128,128,0],yellow:[255,255,0],orange:[255,165,0],gray:[128,128,128],purple:[128,0,128],green:[0,128,0],red:[255,0,0],pink:[255,192,203],cyan:[0,255,255],transparent:[255,255,255,0]},la=function(a,b,c){return a=0>a?a+1:a>1?a-1:a,255*(1>6*a?b+(c-b)*a*6:.5>a?c:2>3*a?b+(c-b)*(2/3-a)*6:b)+.5|0},ma=g.parseColor=function(a,b){var c,d,e,f,g,h,i,j,k,l,m;if(a)if("number"==typeof a)c=[a>>16,a>>8&255,255&a];else{if(","===a.charAt(a.length-1)&&(a=a.substr(0,a.length-1)),ka[a])c=ka[a];else if("#"===a.charAt(0))4===a.length&&(d=a.charAt(1),e=a.charAt(2),f=a.charAt(3),a="#"+d+d+e+e+f+f),a=parseInt(a.substr(1),16),c=[a>>16,a>>8&255,255&a];else if("hsl"===a.substr(0,3))if(c=m=a.match(s),b){if(-1!==a.indexOf("="))return a.match(t)}else g=Number(c[0])%360/360,h=Number(c[1])/100,i=Number(c[2])/100,e=.5>=i?i*(h+1):i+h-i*h,d=2*i-e,c.length>3&&(c[3]=Number(a[3])),c[0]=la(g+1/3,d,e),c[1]=la(g,d,e),c[2]=la(g-1/3,d,e);else c=a.match(s)||ka.transparent;c[0]=Number(c[0]),c[1]=Number(c[1]),c[2]=Number(c[2]),c.length>3&&(c[3]=Number(c[3]))}else c=ka.black;return b&&!m&&(d=c[0]/255,e=c[1]/255,f=c[2]/255,j=Math.max(d,e,f),k=Math.min(d,e,f),i=(j+k)/2,j===k?g=h=0:(l=j-k,h=i>.5?l/(2-j-k):l/(j+k),g=j===d?(e-f)/l+(f>e?6:0):j===e?(f-d)/l+2:(d-e)/l+4,g*=60),c[0]=g+.5|0,c[1]=100*h+.5|0,c[2]=100*i+.5|0),c},na=function(a,b){var c,d,e,f=a.match(oa)||[],g=0,h=f.length?"":a;for(c=0;c<f.length;c++)d=f[c],e=a.substr(g,a.indexOf(d,g)-g),g+=e.length+d.length,d=ma(d,b),3===d.length&&d.push(1),h+=e+(b?"hsla("+d[0]+","+d[1]+"%,"+d[2]+"%,"+d[3]:"rgba("+d.join(","))+")";return h+a.substr(g)},oa="(?:\\b(?:(?:rgb|rgba|hsl|hsla)\\(.+?\\))|\\B#(?:[0-9a-f]{3}){1,2}\\b";for(j in ka)oa+="|"+j+"\\b";oa=new RegExp(oa+")","gi"),g.colorStringFilter=function(a){var b,c=a[0]+a[1];oa.test(c)&&(b=-1!==c.indexOf("hsl(")||-1!==c.indexOf("hsla("),a[0]=na(a[0],b),a[1]=na(a[1],b)),oa.lastIndex=0},b.defaultStringFilter||(b.defaultStringFilter=g.colorStringFilter);var pa=function(a,b,c,d){if(null==a)return function(a){return a};var e,f=b?(a.match(oa)||[""])[0]:"",g=a.split(f).join("").match(u)||[],h=a.substr(0,a.indexOf(g[0])),i=")"===a.charAt(a.length-1)?")":"",j=-1!==a.indexOf(" ")?" ":",",k=g.length,l=k>0?g[0].replace(s,""):"";return k?e=b?function(a){var b,m,n,o;if("number"==typeof a)a+=l;else if(d&&I.test(a)){for(o=a.replace(I,"|").split("|"),n=0;n<o.length;n++)o[n]=e(o[n]);return o.join(",")}if(b=(a.match(oa)||[f])[0],m=a.split(b).join("").match(u)||[],n=m.length,k>n--)for(;++n<k;)m[n]=c?m[(n-1)/2|0]:g[n];return h+m.join(j)+j+b+i+(-1!==a.indexOf("inset")?" inset":"")}:function(a){var b,f,m;if("number"==typeof a)a+=l;else if(d&&I.test(a)){for(f=a.replace(I,"|").split("|"),m=0;m<f.length;m++)f[m]=e(f[m]);return f.join(",")}if(b=a.match(u)||[],m=b.length,k>m--)for(;++m<k;)b[m]=c?b[(m-1)/2|0]:g[m];return h+b.join(j)+i}:function(a){return a}},qa=function(a){return a=a.split(","),function(b,c,d,e,f,g,h){var i,j=(c+"").split(" ");for(h={},i=0;4>i;i++)h[a[i]]=j[i]=j[i]||j[(i-1)/2>>0];return e.parse(b,h,f,g)}},ra=(R._setPluginRatio=function(a){this.plugin.setRatio(a);for(var b,c,d,e,f,g=this.data,h=g.proxy,i=g.firstMPT,j=1e-6;i;)b=h[i.v],i.r?b=Math.round(b):j>b&&b>-j&&(b=0),i.t[i.p]=b,i=i._next;if(g.autoRotate&&(g.autoRotate.rotation=g.mod?g.mod(h.rotation,this.t):h.rotation),1===a||0===a)for(i=g.firstMPT,f=1===a?"e":"b";i;){if(c=i.t,c.type){if(1===c.type){for(e=c.xs0+c.s+c.xs1,d=1;d<c.l;d++)e+=c["xn"+d]+c["xs"+(d+1)];c[f]=e}}else c[f]=c.s+c.xs0;i=i._next}},function(a,b,c,d,e){this.t=a,this.p=b,this.v=c,this.r=e,d&&(d._prev=this,this._next=d)}),sa=(R._parseToProxy=function(a,b,c,d,e,f){var g,h,i,j,k,l=d,m={},n={},o=c._transform,p=M;for(c._transform=null,M=b,d=k=c.parse(a,b,d,e),M=p,f&&(c._transform=o,l&&(l._prev=null,l._prev&&(l._prev._next=null)));d&&d!==l;){if(d.type<=1&&(h=d.p,n[h]=d.s+d.c,m[h]=d.s,f||(j=new ra(d,"s",h,j,d.r),d.c=0),1===d.type))for(g=d.l;--g>0;)i="xn"+g,h=d.p+"_"+i,n[h]=d.data[i],m[h]=d[i],f||(j=new ra(d,i,h,j,d.rxp[i]));d=d._next}return{proxy:m,end:n,firstMPT:j,pt:k}},R.CSSPropTween=function(a,b,d,e,g,h,i,j,k,l,m){this.t=a,this.p=b,this.s=d,this.c=e,this.n=i||b,a instanceof sa||f.push(this.n),this.r=j,this.type=h||0,k&&(this.pr=k,c=!0),this.b=void 0===l?d:l,this.e=void 0===m?d+e:m,g&&(this._next=g,g._prev=this)}),ta=function(a,b,c,d,e,f){var g=new sa(a,b,c,d-c,e,-1,f);return g.b=c,g.e=g.xs0=d,g},ua=g.parseComplex=function(a,b,c,d,e,f,h,i,j,l){c=c||f||"","function"==typeof d&&(d=d(r,q)),h=new sa(a,b,0,0,h,l?2:1,null,!1,i,c,d),d+="",e&&oa.test(d+c)&&(d=[c,d],g.colorStringFilter(d),c=d[0],d=d[1]);var m,n,o,p,u,v,w,x,y,z,A,B,C,D=c.split(", ").join(",").split(" "),E=d.split(", ").join(",").split(" "),F=D.length,G=k!==!1;for((-1!==d.indexOf(",")||-1!==c.indexOf(","))&&(D=D.join(" ").replace(I,", ").split(" "),E=E.join(" ").replace(I,", ").split(" "),F=D.length),F!==E.length&&(D=(f||"").split(" "),F=D.length),h.plugin=j,h.setRatio=l,oa.lastIndex=0,m=0;F>m;m++)if(p=D[m],u=E[m],x=parseFloat(p),x||0===x)h.appendXtra("",x,ha(u,x),u.replace(t,""),G&&-1!==u.indexOf("px"),!0);else if(e&&oa.test(p))B=u.indexOf(")")+1,B=")"+(B?u.substr(B):""),C=-1!==u.indexOf("hsl")&&T,p=ma(p,C),u=ma(u,C),y=p.length+u.length>6,y&&!T&&0===u[3]?(h["xs"+h.l]+=h.l?" transparent":"transparent",h.e=h.e.split(E[m]).join("transparent")):(T||(y=!1),C?h.appendXtra(y?"hsla(":"hsl(",p[0],ha(u[0],p[0]),",",!1,!0).appendXtra("",p[1],ha(u[1],p[1]),"%,",!1).appendXtra("",p[2],ha(u[2],p[2]),y?"%,":"%"+B,!1):h.appendXtra(y?"rgba(":"rgb(",p[0],u[0]-p[0],",",!0,!0).appendXtra("",p[1],u[1]-p[1],",",!0).appendXtra("",p[2],u[2]-p[2],y?",":B,!0),y&&(p=p.length<4?1:p[3],h.appendXtra("",p,(u.length<4?1:u[3])-p,B,!1))),oa.lastIndex=0;else if(v=p.match(s)){if(w=u.match(t),!w||w.length!==v.length)return h;for(o=0,n=0;n<v.length;n++)A=v[n],z=p.indexOf(A,o),h.appendXtra(p.substr(o,z-o),Number(A),ha(w[n],A),"",G&&"px"===p.substr(z+A.length,2),0===n),o=z+A.length;h["xs"+h.l]+=p.substr(o)}else h["xs"+h.l]+=h.l||h["xs"+h.l]?" "+u:u;if(-1!==d.indexOf("=")&&h.data){for(B=h.xs0+h.data.s,m=1;m<h.l;m++)B+=h["xs"+m]+h.data["xn"+m];h.e=B+h["xs"+m]}return h.l||(h.type=-1,h.xs0=h.e),h.xfirst||h},va=9;for(j=sa.prototype,j.l=j.pr=0;--va>0;)j["xn"+va]=0,j["xs"+va]="";j.xs0="",j._next=j._prev=j.xfirst=j.data=j.plugin=j.setRatio=j.rxp=null,j.appendXtra=function(a,b,c,d,e,f){var g=this,h=g.l;return g["xs"+h]+=f&&(h||g["xs"+h])?" "+a:a||"",c||0===h||g.plugin?(g.l++,g.type=g.setRatio?2:1,g["xs"+g.l]=d||"",h>0?(g.data["xn"+h]=b+c,g.rxp["xn"+h]=e,g["xn"+h]=b,g.plugin||(g.xfirst=new sa(g,"xn"+h,b,c,g.xfirst||g,0,g.n,e,g.pr),g.xfirst.xs0=0),g):(g.data={s:b+c},g.rxp={},g.s=b,g.c=c,g.r=e,g)):(g["xs"+h]+=b+(d||""),g)};var wa=function(a,b){b=b||{},this.p=b.prefix?Y(a)||a:a,i[a]=i[this.p]=this,this.format=b.formatter||pa(b.defaultValue,b.color,b.collapsible,b.multi),b.parser&&(this.parse=b.parser),this.clrs=b.color,this.multi=b.multi,this.keyword=b.keyword,this.dflt=b.defaultValue,this.pr=b.priority||0},xa=R._registerComplexSpecialProp=function(a,b,c){"object"!=typeof b&&(b={parser:c});var d,e,f=a.split(","),g=b.defaultValue;for(c=c||[g],d=0;d<f.length;d++)b.prefix=0===d&&b.prefix,b.defaultValue=c[d]||g,e=new wa(f[d],b)},ya=R._registerPluginProp=function(a){if(!i[a]){var b=a.charAt(0).toUpperCase()+a.substr(1)+"Plugin";xa(a,{parser:function(a,c,d,e,f,g,j){var k=h.com.greensock.plugins[b];return k?(k._cssRegister(),i[d].parse(a,c,d,e,f,g,j)):(V("Error: "+b+" js file not loaded."),f)}})}};j=wa.prototype,j.parseComplex=function(a,b,c,d,e,f){var g,h,i,j,k,l,m=this.keyword;if(this.multi&&(I.test(c)||I.test(b)?(h=b.replace(I,"|").split("|"),i=c.replace(I,"|").split("|")):m&&(h=[b],i=[c])),i){for(j=i.length>h.length?i.length:h.length,g=0;j>g;g++)b=h[g]=h[g]||this.dflt,c=i[g]=i[g]||this.dflt,m&&(k=b.indexOf(m),l=c.indexOf(m),k!==l&&(-1===l?h[g]=h[g].split(m).join(""):-1===k&&(h[g]+=" "+m)));b=h.join(", "),c=i.join(", ")}return ua(a,this.p,b,c,this.clrs,this.dflt,d,this.pr,e,f)},j.parse=function(a,b,c,d,f,g,h){return this.parseComplex(a.style,this.format($(a,this.p,e,!1,this.dflt)),this.format(b),f,g)},g.registerSpecialProp=function(a,b,c){xa(a,{parser:function(a,d,e,f,g,h,i){var j=new sa(a,e,0,0,g,2,e,!1,c);return j.plugin=h,j.setRatio=b(a,d,f._tween,e),j},priority:c})},g.useSVGTransformAttr=m||n;var za,Aa="scaleX,scaleY,scaleZ,x,y,z,skewX,skewY,rotation,rotationX,rotationY,perspective,xPercent,yPercent".split(","),Ba=Y("transform"),Ca=W+"transform",Da=Y("transformOrigin"),Ea=null!==Y("perspective"),Fa=R.Transform=function(){this.perspective=parseFloat(g.defaultTransformPerspective)||0,this.force3D=g.defaultForce3D!==!1&&Ea?g.defaultForce3D||"auto":!1},Ga=window.SVGElement,Ha=function(a,b,c){var d,e=N.createElementNS("http://www.w3.org/2000/svg",a),f=/([a-z])([A-Z])/g;for(d in c)e.setAttributeNS(null,d.replace(f,"$1-$2").toLowerCase(),c[d]);return b.appendChild(e),e},Ia=N.documentElement,Ja=function(){var a,b,c,d=p||/Android/i.test(S)&&!window.chrome;return N.createElementNS&&!d&&(a=Ha("svg",Ia),b=Ha("rect",a,{width:100,height:50,x:100}),c=b.getBoundingClientRect().width,b.style[Da]="50% 50%",b.style[Ba]="scaleX(0.5)",d=c===b.getBoundingClientRect().width&&!(n&&Ea),Ia.removeChild(a)),d}(),Ka=function(a,b,c,d,e,f){var h,i,j,k,l,m,n,o,p,q,r,s,t,u,v=a._gsTransform,w=Oa(a,!0);v&&(t=v.xOrigin,u=v.yOrigin),(!d||(h=d.split(" ")).length<2)&&(n=a.getBBox(),b=ga(b).split(" "),h=[(-1!==b[0].indexOf("%")?parseFloat(b[0])/100*n.width:parseFloat(b[0]))+n.x,(-1!==b[1].indexOf("%")?parseFloat(b[1])/100*n.height:parseFloat(b[1]))+n.y]),c.xOrigin=k=parseFloat(h[0]),c.yOrigin=l=parseFloat(h[1]),d&&w!==Na&&(m=w[0],n=w[1],o=w[2],p=w[3],q=w[4],r=w[5],s=m*p-n*o,i=k*(p/s)+l*(-o/s)+(o*r-p*q)/s,j=k*(-n/s)+l*(m/s)-(m*r-n*q)/s,k=c.xOrigin=h[0]=i,l=c.yOrigin=h[1]=j),v&&(f&&(c.xOffset=v.xOffset,c.yOffset=v.yOffset,v=c),e||e!==!1&&g.defaultSmoothOrigin!==!1?(i=k-t,j=l-u,v.xOffset+=i*w[0]+j*w[2]-i,v.yOffset+=i*w[1]+j*w[3]-j):v.xOffset=v.yOffset=0),f||a.setAttribute("data-svg-origin",h.join(" "))},La=function(a){try{return a.getBBox()}catch(a){}},Ma=function(a){return!!(Ga&&a.getBBox&&a.getCTM&&La(a)&&(!a.parentNode||a.parentNode.getBBox&&a.parentNode.getCTM))},Na=[1,0,0,1,0,0],Oa=function(a,b){var c,d,e,f,g,h,i=a._gsTransform||new Fa,j=1e5,k=a.style;if(Ba?d=$(a,Ca,null,!0):a.currentStyle&&(d=a.currentStyle.filter.match(G),d=d&&4===d.length?[d[0].substr(4),Number(d[2].substr(4)),Number(d[1].substr(4)),d[3].substr(4),i.x||0,i.y||0].join(","):""),c=!d||"none"===d||"matrix(1, 0, 0, 1, 0, 0)"===d,c&&Ba&&((h="none"===Z(a).display)||!a.parentNode)&&(h&&(f=k.display,k.display="block"),a.parentNode||(g=1,Ia.appendChild(a)),d=$(a,Ca,null,!0),c=!d||"none"===d||"matrix(1, 0, 0, 1, 0, 0)"===d,f?k.display=f:h&&Ta(k,"display"),g&&Ia.removeChild(a)),(i.svg||a.getBBox&&Ma(a))&&(c&&-1!==(k[Ba]+"").indexOf("matrix")&&(d=k[Ba],c=0),e=a.getAttribute("transform"),c&&e&&(-1!==e.indexOf("matrix")?(d=e,c=0):-1!==e.indexOf("translate")&&(d="matrix(1,0,0,1,"+e.match(/(?:\-|\b)[\d\-\.e]+\b/gi).join(",")+")",c=0))),c)return Na;for(e=(d||"").match(s)||[],va=e.length;--va>-1;)f=Number(e[va]),e[va]=(g=f-(f|=0))?(g*j+(0>g?-.5:.5)|0)/j+f:f;return b&&e.length>6?[e[0],e[1],e[4],e[5],e[12],e[13]]:e},Pa=R.getTransform=function(a,c,d,e){if(a._gsTransform&&d&&!e)return a._gsTransform;var f,h,i,j,k,l,m=d?a._gsTransform||new Fa:new Fa,n=m.scaleX<0,o=2e-5,p=1e5,q=Ea?parseFloat($(a,Da,c,!1,"0 0 0").split(" ")[2])||m.zOrigin||0:0,r=parseFloat(g.defaultTransformPerspective)||0;if(m.svg=!(!a.getBBox||!Ma(a)),m.svg&&(Ka(a,$(a,Da,c,!1,"50% 50%")+"",m,a.getAttribute("data-svg-origin")),za=g.useSVGTransformAttr||Ja),f=Oa(a),f!==Na){if(16===f.length){var s,t,u,v,w,x=f[0],y=f[1],z=f[2],A=f[3],B=f[4],C=f[5],D=f[6],E=f[7],F=f[8],G=f[9],H=f[10],I=f[12],J=f[13],K=f[14],M=f[11],N=Math.atan2(D,H);m.zOrigin&&(K=-m.zOrigin,I=F*K-f[12],J=G*K-f[13],K=H*K+m.zOrigin-f[14]),m.rotationX=N*L,N&&(v=Math.cos(-N),w=Math.sin(-N),s=B*v+F*w,t=C*v+G*w,u=D*v+H*w,F=B*-w+F*v,G=C*-w+G*v,H=D*-w+H*v,M=E*-w+M*v,B=s,C=t,D=u),N=Math.atan2(-z,H),m.rotationY=N*L,N&&(v=Math.cos(-N),w=Math.sin(-N),s=x*v-F*w,t=y*v-G*w,u=z*v-H*w,G=y*w+G*v,H=z*w+H*v,M=A*w+M*v,x=s,y=t,z=u),N=Math.atan2(y,x),m.rotation=N*L,N&&(v=Math.cos(-N),w=Math.sin(-N),x=x*v+B*w,t=y*v+C*w,C=y*-w+C*v,D=z*-w+D*v,y=t),m.rotationX&&Math.abs(m.rotationX)+Math.abs(m.rotation)>359.9&&(m.rotationX=m.rotation=0,m.rotationY=180-m.rotationY),m.scaleX=(Math.sqrt(x*x+y*y)*p+.5|0)/p,m.scaleY=(Math.sqrt(C*C+G*G)*p+.5|0)/p,m.scaleZ=(Math.sqrt(D*D+H*H)*p+.5|0)/p,m.rotationX||m.rotationY?m.skewX=0:(m.skewX=B||C?Math.atan2(B,C)*L+m.rotation:m.skewX||0,Math.abs(m.skewX)>90&&Math.abs(m.skewX)<270&&(n?(m.scaleX*=-1,m.skewX+=m.rotation<=0?180:-180,m.rotation+=m.rotation<=0?180:-180):(m.scaleY*=-1,m.skewX+=m.skewX<=0?180:-180))),m.perspective=M?1/(0>M?-M:M):0,m.x=I,m.y=J,m.z=K,m.svg&&(m.x-=m.xOrigin-(m.xOrigin*x-m.yOrigin*B),m.y-=m.yOrigin-(m.yOrigin*y-m.xOrigin*C))}else if(!Ea||e||!f.length||m.x!==f[4]||m.y!==f[5]||!m.rotationX&&!m.rotationY){var O=f.length>=6,P=O?f[0]:1,Q=f[1]||0,R=f[2]||0,S=O?f[3]:1;m.x=f[4]||0,m.y=f[5]||0,i=Math.sqrt(P*P+Q*Q),j=Math.sqrt(S*S+R*R),k=P||Q?Math.atan2(Q,P)*L:m.rotation||0,l=R||S?Math.atan2(R,S)*L+k:m.skewX||0,Math.abs(l)>90&&Math.abs(l)<270&&(n?(i*=-1,l+=0>=k?180:-180,k+=0>=k?180:-180):(j*=-1,l+=0>=l?180:-180)),m.scaleX=i,m.scaleY=j,m.rotation=k,m.skewX=l,Ea&&(m.rotationX=m.rotationY=m.z=0,m.perspective=r,m.scaleZ=1),m.svg&&(m.x-=m.xOrigin-(m.xOrigin*P+m.yOrigin*R),m.y-=m.yOrigin-(m.xOrigin*Q+m.yOrigin*S))}m.zOrigin=q;for(h in m)m[h]<o&&m[h]>-o&&(m[h]=0)}return d&&(a._gsTransform=m,m.svg&&(za&&a.style[Ba]?b.delayedCall(.001,function(){Ta(a.style,Ba)}):!za&&a.getAttribute("transform")&&b.delayedCall(.001,function(){a.removeAttribute("transform")}))),m},Qa=function(a){var b,c,d=this.data,e=-d.rotation*K,f=e+d.skewX*K,g=1e5,h=(Math.cos(e)*d.scaleX*g|0)/g,i=(Math.sin(e)*d.scaleX*g|0)/g,j=(Math.sin(f)*-d.scaleY*g|0)/g,k=(Math.cos(f)*d.scaleY*g|0)/g,l=this.t.style,m=this.t.currentStyle;if(m){c=i,i=-j,j=-c,b=m.filter,l.filter="";var n,o,q=this.t.offsetWidth,r=this.t.offsetHeight,s="absolute"!==m.position,t="progid:DXImageTransform.Microsoft.Matrix(M11="+h+", M12="+i+", M21="+j+", M22="+k,u=d.x+q*d.xPercent/100,v=d.y+r*d.yPercent/100;if(null!=d.ox&&(n=(d.oxp?q*d.ox*.01:d.ox)-q/2,o=(d.oyp?r*d.oy*.01:d.oy)-r/2,u+=n-(n*h+o*i),v+=o-(n*j+o*k)),s?(n=q/2,o=r/2,t+=", Dx="+(n-(n*h+o*i)+u)+", Dy="+(o-(n*j+o*k)+v)+")"):t+=", sizingMethod='auto expand')",-1!==b.indexOf("DXImageTransform.Microsoft.Matrix(")?l.filter=b.replace(H,t):l.filter=t+" "+b,(0===a||1===a)&&1===h&&0===i&&0===j&&1===k&&(s&&-1===t.indexOf("Dx=0, Dy=0")||x.test(b)&&100!==parseFloat(RegExp.$1)||-1===b.indexOf(b.indexOf("Alpha"))&&l.removeAttribute("filter")),!s){var y,z,A,B=8>p?1:-1;for(n=d.ieOffsetX||0,o=d.ieOffsetY||0,d.ieOffsetX=Math.round((q-((0>h?-h:h)*q+(0>i?-i:i)*r))/2+u),d.ieOffsetY=Math.round((r-((0>k?-k:k)*r+(0>j?-j:j)*q))/2+v),va=0;4>va;va++)z=ea[va],y=m[z],c=-1!==y.indexOf("px")?parseFloat(y):_(this.t,z,parseFloat(y),y.replace(w,""))||0,A=c!==d[z]?2>va?-d.ieOffsetX:-d.ieOffsetY:2>va?n-d.ieOffsetX:o-d.ieOffsetY,l[z]=(d[z]=Math.round(c-A*(0===va||2===va?1:B)))+"px"}}},Ra=R.set3DTransformRatio=R.setTransformRatio=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,o,p,q,r,s,t,u,v,w,x,y,z=this.data,A=this.t.style,B=z.rotation,C=z.rotationX,D=z.rotationY,E=z.scaleX,F=z.scaleY,G=z.scaleZ,H=z.x,I=z.y,J=z.z,L=z.svg,M=z.perspective,N=z.force3D;if(((1===a||0===a)&&"auto"===N&&(this.tween._totalTime===this.tween._totalDuration||!this.tween._totalTime)||!N)&&!J&&!M&&!D&&!C&&1===G||za&&L||!Ea)return void(B||z.skewX||L?(B*=K,x=z.skewX*K,y=1e5,b=Math.cos(B)*E,e=Math.sin(B)*E,c=Math.sin(B-x)*-F,f=Math.cos(B-x)*F,x&&"simple"===z.skewType&&(s=Math.tan(x-z.skewY*K),s=Math.sqrt(1+s*s),c*=s,f*=s,z.skewY&&(s=Math.tan(z.skewY*K),s=Math.sqrt(1+s*s),b*=s,e*=s)),L&&(H+=z.xOrigin-(z.xOrigin*b+z.yOrigin*c)+z.xOffset,I+=z.yOrigin-(z.xOrigin*e+z.yOrigin*f)+z.yOffset,za&&(z.xPercent||z.yPercent)&&(p=this.t.getBBox(),H+=.01*z.xPercent*p.width,I+=.01*z.yPercent*p.height),p=1e-6,p>H&&H>-p&&(H=0),p>I&&I>-p&&(I=0)),u=(b*y|0)/y+","+(e*y|0)/y+","+(c*y|0)/y+","+(f*y|0)/y+","+H+","+I+")",L&&za?this.t.setAttribute("transform","matrix("+u):A[Ba]=(z.xPercent||z.yPercent?"translate("+z.xPercent+"%,"+z.yPercent+"%) matrix(":"matrix(")+u):A[Ba]=(z.xPercent||z.yPercent?"translate("+z.xPercent+"%,"+z.yPercent+"%) matrix(":"matrix(")+E+",0,0,"+F+","+H+","+I+")");if(n&&(p=1e-4,p>E&&E>-p&&(E=G=2e-5),p>F&&F>-p&&(F=G=2e-5),!M||z.z||z.rotationX||z.rotationY||(M=0)),B||z.skewX)B*=K,q=b=Math.cos(B),r=e=Math.sin(B),z.skewX&&(B-=z.skewX*K,q=Math.cos(B),r=Math.sin(B),"simple"===z.skewType&&(s=Math.tan((z.skewX-z.skewY)*K),s=Math.sqrt(1+s*s),q*=s,r*=s,z.skewY&&(s=Math.tan(z.skewY*K),s=Math.sqrt(1+s*s),b*=s,e*=s))),c=-r,f=q;else{if(!(D||C||1!==G||M||L))return void(A[Ba]=(z.xPercent||z.yPercent?"translate("+z.xPercent+"%,"+z.yPercent+"%) translate3d(":"translate3d(")+H+"px,"+I+"px,"+J+"px)"+(1!==E||1!==F?" scale("+E+","+F+")":""));b=f=1,c=e=0}j=1,d=g=h=i=k=l=0,m=M?-1/M:0,o=z.zOrigin,p=1e-6,v=",",w="0",B=D*K,B&&(q=Math.cos(B),r=Math.sin(B),h=-r,k=m*-r,d=b*r,g=e*r,j=q,m*=q,b*=q,e*=q),B=C*K,B&&(q=Math.cos(B),r=Math.sin(B),s=c*q+d*r,t=f*q+g*r,i=j*r,l=m*r,d=c*-r+d*q,g=f*-r+g*q,j*=q,m*=q,c=s,f=t),1!==G&&(d*=G,g*=G,j*=G,m*=G),1!==F&&(c*=F,f*=F,i*=F,l*=F),1!==E&&(b*=E,e*=E,h*=E,k*=E),(o||L)&&(o&&(H+=d*-o,I+=g*-o,J+=j*-o+o),L&&(H+=z.xOrigin-(z.xOrigin*b+z.yOrigin*c)+z.xOffset,I+=z.yOrigin-(z.xOrigin*e+z.yOrigin*f)+z.yOffset),p>H&&H>-p&&(H=w),p>I&&I>-p&&(I=w),p>J&&J>-p&&(J=0)),u=z.xPercent||z.yPercent?"translate("+z.xPercent+"%,"+z.yPercent+"%) matrix3d(":"matrix3d(",u+=(p>b&&b>-p?w:b)+v+(p>e&&e>-p?w:e)+v+(p>h&&h>-p?w:h),u+=v+(p>k&&k>-p?w:k)+v+(p>c&&c>-p?w:c)+v+(p>f&&f>-p?w:f),C||D||1!==G?(u+=v+(p>i&&i>-p?w:i)+v+(p>l&&l>-p?w:l)+v+(p>d&&d>-p?w:d),u+=v+(p>g&&g>-p?w:g)+v+(p>j&&j>-p?w:j)+v+(p>m&&m>-p?w:m)+v):u+=",0,0,0,0,1,0,",u+=H+v+I+v+J+v+(M?1+-J/M:1)+")",A[Ba]=u};j=Fa.prototype,j.x=j.y=j.z=j.skewX=j.skewY=j.rotation=j.rotationX=j.rotationY=j.zOrigin=j.xPercent=j.yPercent=j.xOffset=j.yOffset=0,j.scaleX=j.scaleY=j.scaleZ=1,xa("transform,scale,scaleX,scaleY,scaleZ,x,y,z,rotation,rotationX,rotationY,rotationZ,skewX,skewY,shortRotation,shortRotationX,shortRotationY,shortRotationZ,transformOrigin,svgOrigin,transformPerspective,directionalRotation,parseTransform,force3D,skewType,xPercent,yPercent,smoothOrigin",{parser:function(a,b,c,d,f,h,i){if(d._lastParsedTransform===i)return f;d._lastParsedTransform=i;var j;"function"==typeof i[c]&&(j=i[c],i[c]=b);var k,l,m,n,o,p,s,t,u,v=a._gsTransform,w=a.style,x=1e-6,y=Aa.length,z=i,A={},B="transformOrigin",C=Pa(a,e,!0,z.parseTransform),D=z.transform&&("function"==typeof z.transform?z.transform(r,q):z.transform);if(d._transform=C,D&&"string"==typeof D&&Ba)l=P.style,l[Ba]=D,l.display="block",l.position="absolute",N.body.appendChild(P),k=Pa(P,null,!1),C.svg&&(p=C.xOrigin,s=C.yOrigin,k.x-=C.xOffset,k.y-=C.yOffset,(z.transformOrigin||z.svgOrigin)&&(D={},Ka(a,ga(z.transformOrigin),D,z.svgOrigin,z.smoothOrigin,!0),p=D.xOrigin,s=D.yOrigin,k.x-=D.xOffset-C.xOffset,k.y-=D.yOffset-C.yOffset),(p||s)&&(t=Oa(P,!0),k.x-=p-(p*t[0]+s*t[2]),k.y-=s-(p*t[1]+s*t[3]))),N.body.removeChild(P),k.perspective||(k.perspective=C.perspective),null!=z.xPercent&&(k.xPercent=ia(z.xPercent,C.xPercent)),null!=z.yPercent&&(k.yPercent=ia(z.yPercent,C.yPercent));else if("object"==typeof z){if(k={scaleX:ia(null!=z.scaleX?z.scaleX:z.scale,C.scaleX),scaleY:ia(null!=z.scaleY?z.scaleY:z.scale,C.scaleY),scaleZ:ia(z.scaleZ,C.scaleZ),x:ia(z.x,C.x),y:ia(z.y,C.y),z:ia(z.z,C.z),xPercent:ia(z.xPercent,C.xPercent),yPercent:ia(z.yPercent,C.yPercent),perspective:ia(z.transformPerspective,C.perspective)},o=z.directionalRotation,null!=o)if("object"==typeof o)for(l in o)z[l]=o[l];else z.rotation=o;"string"==typeof z.x&&-1!==z.x.indexOf("%")&&(k.x=0,k.xPercent=ia(z.x,C.xPercent)),"string"==typeof z.y&&-1!==z.y.indexOf("%")&&(k.y=0,k.yPercent=ia(z.y,C.yPercent)),k.rotation=ja("rotation"in z?z.rotation:"shortRotation"in z?z.shortRotation+"_short":"rotationZ"in z?z.rotationZ:C.rotation-C.skewY,C.rotation-C.skewY,"rotation",A),Ea&&(k.rotationX=ja("rotationX"in z?z.rotationX:"shortRotationX"in z?z.shortRotationX+"_short":C.rotationX||0,C.rotationX,"rotationX",A),k.rotationY=ja("rotationY"in z?z.rotationY:"shortRotationY"in z?z.shortRotationY+"_short":C.rotationY||0,C.rotationY,"rotationY",A)),k.skewX=ja(z.skewX,C.skewX-C.skewY),(k.skewY=ja(z.skewY,C.skewY))&&(k.skewX+=k.skewY,k.rotation+=k.skewY)}for(Ea&&null!=z.force3D&&(C.force3D=z.force3D,n=!0),C.skewType=z.skewType||C.skewType||g.defaultSkewType,m=C.force3D||C.z||C.rotationX||C.rotationY||k.z||k.rotationX||k.rotationY||k.perspective,m||null==z.scale||(k.scaleZ=1);--y>-1;)u=Aa[y],D=k[u]-C[u],(D>x||-x>D||null!=z[u]||null!=M[u])&&(n=!0,
f=new sa(C,u,C[u],D,f),u in A&&(f.e=A[u]),f.xs0=0,f.plugin=h,d._overwriteProps.push(f.n));return D=z.transformOrigin,C.svg&&(D||z.svgOrigin)&&(p=C.xOffset,s=C.yOffset,Ka(a,ga(D),k,z.svgOrigin,z.smoothOrigin),f=ta(C,"xOrigin",(v?C:k).xOrigin,k.xOrigin,f,B),f=ta(C,"yOrigin",(v?C:k).yOrigin,k.yOrigin,f,B),(p!==C.xOffset||s!==C.yOffset)&&(f=ta(C,"xOffset",v?p:C.xOffset,C.xOffset,f,B),f=ta(C,"yOffset",v?s:C.yOffset,C.yOffset,f,B)),D=za?null:"0px 0px"),(D||Ea&&m&&C.zOrigin)&&(Ba?(n=!0,u=Da,D=(D||$(a,u,e,!1,"50% 50%"))+"",f=new sa(w,u,0,0,f,-1,B),f.b=w[u],f.plugin=h,Ea?(l=C.zOrigin,D=D.split(" "),C.zOrigin=(D.length>2&&(0===l||"0px"!==D[2])?parseFloat(D[2]):l)||0,f.xs0=f.e=D[0]+" "+(D[1]||"50%")+" 0px",f=new sa(C,"zOrigin",0,0,f,-1,f.n),f.b=l,f.xs0=f.e=C.zOrigin):f.xs0=f.e=D):ga(D+"",C)),n&&(d._transformType=C.svg&&za||!m&&3!==this._transformType?2:3),j&&(i[c]=j),f},prefix:!0}),xa("boxShadow",{defaultValue:"0px 0px 0px 0px #999",prefix:!0,color:!0,multi:!0,keyword:"inset"}),xa("borderRadius",{defaultValue:"0px",parser:function(a,b,c,f,g,h){b=this.format(b);var i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y=["borderTopLeftRadius","borderTopRightRadius","borderBottomRightRadius","borderBottomLeftRadius"],z=a.style;for(q=parseFloat(a.offsetWidth),r=parseFloat(a.offsetHeight),i=b.split(" "),j=0;j<y.length;j++)this.p.indexOf("border")&&(y[j]=Y(y[j])),m=l=$(a,y[j],e,!1,"0px"),-1!==m.indexOf(" ")&&(l=m.split(" "),m=l[0],l=l[1]),n=k=i[j],o=parseFloat(m),t=m.substr((o+"").length),u="="===n.charAt(1),u?(p=parseInt(n.charAt(0)+"1",10),n=n.substr(2),p*=parseFloat(n),s=n.substr((p+"").length-(0>p?1:0))||""):(p=parseFloat(n),s=n.substr((p+"").length)),""===s&&(s=d[c]||t),s!==t&&(v=_(a,"borderLeft",o,t),w=_(a,"borderTop",o,t),"%"===s?(m=v/q*100+"%",l=w/r*100+"%"):"em"===s?(x=_(a,"borderLeft",1,"em"),m=v/x+"em",l=w/x+"em"):(m=v+"px",l=w+"px"),u&&(n=parseFloat(m)+p+s,k=parseFloat(l)+p+s)),g=ua(z,y[j],m+" "+l,n+" "+k,!1,"0px",g);return g},prefix:!0,formatter:pa("0px 0px 0px 0px",!1,!0)}),xa("borderBottomLeftRadius,borderBottomRightRadius,borderTopLeftRadius,borderTopRightRadius",{defaultValue:"0px",parser:function(a,b,c,d,f,g){return ua(a.style,c,this.format($(a,c,e,!1,"0px 0px")),this.format(b),!1,"0px",f)},prefix:!0,formatter:pa("0px 0px",!1,!0)}),xa("backgroundPosition",{defaultValue:"0 0",parser:function(a,b,c,d,f,g){var h,i,j,k,l,m,n="background-position",o=e||Z(a,null),q=this.format((o?p?o.getPropertyValue(n+"-x")+" "+o.getPropertyValue(n+"-y"):o.getPropertyValue(n):a.currentStyle.backgroundPositionX+" "+a.currentStyle.backgroundPositionY)||"0 0"),r=this.format(b);if(-1!==q.indexOf("%")!=(-1!==r.indexOf("%"))&&r.split(",").length<2&&(m=$(a,"backgroundImage").replace(D,""),m&&"none"!==m)){for(h=q.split(" "),i=r.split(" "),Q.setAttribute("src",m),j=2;--j>-1;)q=h[j],k=-1!==q.indexOf("%"),k!==(-1!==i[j].indexOf("%"))&&(l=0===j?a.offsetWidth-Q.width:a.offsetHeight-Q.height,h[j]=k?parseFloat(q)/100*l+"px":parseFloat(q)/l*100+"%");q=h.join(" ")}return this.parseComplex(a.style,q,r,f,g)},formatter:ga}),xa("backgroundSize",{defaultValue:"0 0",formatter:function(a){return a+="",ga(-1===a.indexOf(" ")?a+" "+a:a)}}),xa("perspective",{defaultValue:"0px",prefix:!0}),xa("perspectiveOrigin",{defaultValue:"50% 50%",prefix:!0}),xa("transformStyle",{prefix:!0}),xa("backfaceVisibility",{prefix:!0}),xa("userSelect",{prefix:!0}),xa("margin",{parser:qa("marginTop,marginRight,marginBottom,marginLeft")}),xa("padding",{parser:qa("paddingTop,paddingRight,paddingBottom,paddingLeft")}),xa("clip",{defaultValue:"rect(0px,0px,0px,0px)",parser:function(a,b,c,d,f,g){var h,i,j;return 9>p?(i=a.currentStyle,j=8>p?" ":",",h="rect("+i.clipTop+j+i.clipRight+j+i.clipBottom+j+i.clipLeft+")",b=this.format(b).split(",").join(j)):(h=this.format($(a,this.p,e,!1,this.dflt)),b=this.format(b)),this.parseComplex(a.style,h,b,f,g)}}),xa("textShadow",{defaultValue:"0px 0px 0px #999",color:!0,multi:!0}),xa("autoRound,strictUnits",{parser:function(a,b,c,d,e){return e}}),xa("border",{defaultValue:"0px solid #000",parser:function(a,b,c,d,f,g){var h=$(a,"borderTopWidth",e,!1,"0px"),i=this.format(b).split(" "),j=i[0].replace(w,"");return"px"!==j&&(h=parseFloat(h)/_(a,"borderTopWidth",1,j)+j),this.parseComplex(a.style,this.format(h+" "+$(a,"borderTopStyle",e,!1,"solid")+" "+$(a,"borderTopColor",e,!1,"#000")),i.join(" "),f,g)},color:!0,formatter:function(a){var b=a.split(" ");return b[0]+" "+(b[1]||"solid")+" "+(a.match(oa)||["#000"])[0]}}),xa("borderWidth",{parser:qa("borderTopWidth,borderRightWidth,borderBottomWidth,borderLeftWidth")}),xa("float,cssFloat,styleFloat",{parser:function(a,b,c,d,e,f){var g=a.style,h="cssFloat"in g?"cssFloat":"styleFloat";return new sa(g,h,0,0,e,-1,c,!1,0,g[h],b)}});var Sa=function(a){var b,c=this.t,d=c.filter||$(this.data,"filter")||"",e=this.s+this.c*a|0;100===e&&(-1===d.indexOf("atrix(")&&-1===d.indexOf("radient(")&&-1===d.indexOf("oader(")?(c.removeAttribute("filter"),b=!$(this.data,"filter")):(c.filter=d.replace(z,""),b=!0)),b||(this.xn1&&(c.filter=d=d||"alpha(opacity="+e+")"),-1===d.indexOf("pacity")?0===e&&this.xn1||(c.filter=d+" alpha(opacity="+e+")"):c.filter=d.replace(x,"opacity="+e))};xa("opacity,alpha,autoAlpha",{defaultValue:"1",parser:function(a,b,c,d,f,g){var h=parseFloat($(a,"opacity",e,!1,"1")),i=a.style,j="autoAlpha"===c;return"string"==typeof b&&"="===b.charAt(1)&&(b=("-"===b.charAt(0)?-1:1)*parseFloat(b.substr(2))+h),j&&1===h&&"hidden"===$(a,"visibility",e)&&0!==b&&(h=0),T?f=new sa(i,"opacity",h,b-h,f):(f=new sa(i,"opacity",100*h,100*(b-h),f),f.xn1=j?1:0,i.zoom=1,f.type=2,f.b="alpha(opacity="+f.s+")",f.e="alpha(opacity="+(f.s+f.c)+")",f.data=a,f.plugin=g,f.setRatio=Sa),j&&(f=new sa(i,"visibility",0,0,f,-1,null,!1,0,0!==h?"inherit":"hidden",0===b?"hidden":"inherit"),f.xs0="inherit",d._overwriteProps.push(f.n),d._overwriteProps.push(c)),f}});var Ta=function(a,b){b&&(a.removeProperty?(("ms"===b.substr(0,2)||"webkit"===b.substr(0,6))&&(b="-"+b),a.removeProperty(b.replace(B,"-$1").toLowerCase())):a.removeAttribute(b))},Ua=function(a){if(this.t._gsClassPT=this,1===a||0===a){this.t.setAttribute("class",0===a?this.b:this.e);for(var b=this.data,c=this.t.style;b;)b.v?c[b.p]=b.v:Ta(c,b.p),b=b._next;1===a&&this.t._gsClassPT===this&&(this.t._gsClassPT=null)}else this.t.getAttribute("class")!==this.e&&this.t.setAttribute("class",this.e)};xa("className",{parser:function(a,b,d,f,g,h,i){var j,k,l,m,n,o=a.getAttribute("class")||"",p=a.style.cssText;if(g=f._classNamePT=new sa(a,d,0,0,g,2),g.setRatio=Ua,g.pr=-11,c=!0,g.b=o,k=ba(a,e),l=a._gsClassPT){for(m={},n=l.data;n;)m[n.p]=1,n=n._next;l.setRatio(1)}return a._gsClassPT=g,g.e="="!==b.charAt(1)?b:o.replace(new RegExp("(?:\\s|^)"+b.substr(2)+"(?![\\w-])"),"")+("+"===b.charAt(0)?" "+b.substr(2):""),a.setAttribute("class",g.e),j=ca(a,k,ba(a),i,m),a.setAttribute("class",o),g.data=j.firstMPT,a.style.cssText=p,g=g.xfirst=f.parse(a,j.difs,g,h)}});var Va=function(a){if((1===a||0===a)&&this.data._totalTime===this.data._totalDuration&&"isFromStart"!==this.data.data){var b,c,d,e,f,g=this.t.style,h=i.transform.parse;if("all"===this.e)g.cssText="",e=!0;else for(b=this.e.split(" ").join("").split(","),d=b.length;--d>-1;)c=b[d],i[c]&&(i[c].parse===h?e=!0:c="transformOrigin"===c?Da:i[c].p),Ta(g,c);e&&(Ta(g,Ba),f=this.t._gsTransform,f&&(f.svg&&(this.t.removeAttribute("data-svg-origin"),this.t.removeAttribute("transform")),delete this.t._gsTransform))}};for(xa("clearProps",{parser:function(a,b,d,e,f){return f=new sa(a,d,0,0,f,2),f.setRatio=Va,f.e=b,f.pr=-10,f.data=e._tween,c=!0,f}}),j="bezier,throwProps,physicsProps,physics2D".split(","),va=j.length;va--;)ya(j[va]);j=g.prototype,j._firstPT=j._lastParsedTransform=j._transform=null,j._onInitTween=function(a,b,h,j){if(!a.nodeType)return!1;this._target=q=a,this._tween=h,this._vars=b,r=j,k=b.autoRound,c=!1,d=b.suffixMap||g.suffixMap,e=Z(a,""),f=this._overwriteProps;var n,p,s,t,u,v,w,x,z,A=a.style;if(l&&""===A.zIndex&&(n=$(a,"zIndex",e),("auto"===n||""===n)&&this._addLazySet(A,"zIndex",0)),"string"==typeof b&&(t=A.cssText,n=ba(a,e),A.cssText=t+";"+b,n=ca(a,n,ba(a)).difs,!T&&y.test(b)&&(n.opacity=parseFloat(RegExp.$1)),b=n,A.cssText=t),b.className?this._firstPT=p=i.className.parse(a,b.className,"className",this,null,null,b):this._firstPT=p=this.parse(a,b,null),this._transformType){for(z=3===this._transformType,Ba?m&&(l=!0,""===A.zIndex&&(w=$(a,"zIndex",e),("auto"===w||""===w)&&this._addLazySet(A,"zIndex",0)),o&&this._addLazySet(A,"WebkitBackfaceVisibility",this._vars.WebkitBackfaceVisibility||(z?"visible":"hidden"))):A.zoom=1,s=p;s&&s._next;)s=s._next;x=new sa(a,"transform",0,0,null,2),this._linkCSSP(x,null,s),x.setRatio=Ba?Ra:Qa,x.data=this._transform||Pa(a,e,!0),x.tween=h,x.pr=-1,f.pop()}if(c){for(;p;){for(v=p._next,s=t;s&&s.pr>p.pr;)s=s._next;(p._prev=s?s._prev:u)?p._prev._next=p:t=p,(p._next=s)?s._prev=p:u=p,p=v}this._firstPT=t}return!0},j.parse=function(a,b,c,f){var g,h,j,l,m,n,o,p,s,t,u=a.style;for(g in b)n=b[g],"function"==typeof n&&(n=n(r,q)),h=i[g],h?c=h.parse(a,n,g,this,c,f,b):(m=$(a,g,e)+"",s="string"==typeof n,"color"===g||"fill"===g||"stroke"===g||-1!==g.indexOf("Color")||s&&A.test(n)?(s||(n=ma(n),n=(n.length>3?"rgba(":"rgb(")+n.join(",")+")"),c=ua(u,g,m,n,!0,"transparent",c,0,f)):s&&J.test(n)?c=ua(u,g,m,n,!0,null,c,0,f):(j=parseFloat(m),o=j||0===j?m.substr((j+"").length):"",(""===m||"auto"===m)&&("width"===g||"height"===g?(j=fa(a,g,e),o="px"):"left"===g||"top"===g?(j=aa(a,g,e),o="px"):(j="opacity"!==g?0:1,o="")),t=s&&"="===n.charAt(1),t?(l=parseInt(n.charAt(0)+"1",10),n=n.substr(2),l*=parseFloat(n),p=n.replace(w,"")):(l=parseFloat(n),p=s?n.replace(w,""):""),""===p&&(p=g in d?d[g]:o),n=l||0===l?(t?l+j:l)+p:b[g],o!==p&&""!==p&&(l||0===l)&&j&&(j=_(a,g,j,o),"%"===p?(j/=_(a,g,100,"%")/100,b.strictUnits!==!0&&(m=j+"%")):"em"===p||"rem"===p||"vw"===p||"vh"===p?j/=_(a,g,1,p):"px"!==p&&(l=_(a,g,l,p),p="px"),t&&(l||0===l)&&(n=l+j+p)),t&&(l+=j),!j&&0!==j||!l&&0!==l?void 0!==u[g]&&(n||n+""!="NaN"&&null!=n)?(c=new sa(u,g,l||j||0,0,c,-1,g,!1,0,m,n),c.xs0="none"!==n||"display"!==g&&-1===g.indexOf("Style")?n:m):V("invalid "+g+" tween value: "+b[g]):(c=new sa(u,g,j,l-j,c,0,g,k!==!1&&("px"===p||"zIndex"===g),0,m,n),c.xs0=p))),f&&c&&!c.plugin&&(c.plugin=f);return c},j.setRatio=function(a){var b,c,d,e=this._firstPT,f=1e-6;if(1!==a||this._tween._time!==this._tween._duration&&0!==this._tween._time)if(a||this._tween._time!==this._tween._duration&&0!==this._tween._time||this._tween._rawPrevTime===-1e-6)for(;e;){if(b=e.c*a+e.s,e.r?b=Math.round(b):f>b&&b>-f&&(b=0),e.type)if(1===e.type)if(d=e.l,2===d)e.t[e.p]=e.xs0+b+e.xs1+e.xn1+e.xs2;else if(3===d)e.t[e.p]=e.xs0+b+e.xs1+e.xn1+e.xs2+e.xn2+e.xs3;else if(4===d)e.t[e.p]=e.xs0+b+e.xs1+e.xn1+e.xs2+e.xn2+e.xs3+e.xn3+e.xs4;else if(5===d)e.t[e.p]=e.xs0+b+e.xs1+e.xn1+e.xs2+e.xn2+e.xs3+e.xn3+e.xs4+e.xn4+e.xs5;else{for(c=e.xs0+b+e.xs1,d=1;d<e.l;d++)c+=e["xn"+d]+e["xs"+(d+1)];e.t[e.p]=c}else-1===e.type?e.t[e.p]=e.xs0:e.setRatio&&e.setRatio(a);else e.t[e.p]=b+e.xs0;e=e._next}else for(;e;)2!==e.type?e.t[e.p]=e.b:e.setRatio(a),e=e._next;else for(;e;){if(2!==e.type)if(e.r&&-1!==e.type)if(b=Math.round(e.s+e.c),e.type){if(1===e.type){for(d=e.l,c=e.xs0+b+e.xs1,d=1;d<e.l;d++)c+=e["xn"+d]+e["xs"+(d+1)];e.t[e.p]=c}}else e.t[e.p]=b+e.xs0;else e.t[e.p]=e.e;else e.setRatio(a);e=e._next}},j._enableTransforms=function(a){this._transform=this._transform||Pa(this._target,e,!0),this._transformType=this._transform.svg&&za||!a&&3!==this._transformType?2:3};var Wa=function(a){this.t[this.p]=this.e,this.data._linkCSSP(this,this._next,null,!0)};j._addLazySet=function(a,b,c){var d=this._firstPT=new sa(a,b,0,0,this._firstPT,2);d.e=c,d.setRatio=Wa,d.data=this},j._linkCSSP=function(a,b,c,d){return a&&(b&&(b._prev=a),a._next&&(a._next._prev=a._prev),a._prev?a._prev._next=a._next:this._firstPT===a&&(this._firstPT=a._next,d=!0),c?c._next=a:d||null!==this._firstPT||(this._firstPT=a),a._next=b,a._prev=c),a},j._mod=function(a){for(var b=this._firstPT;b;)"function"==typeof a[b.p]&&a[b.p]===Math.round&&(b.r=1),b=b._next},j._kill=function(b){var c,d,e,f=b;if(b.autoAlpha||b.alpha){f={};for(d in b)f[d]=b[d];f.opacity=1,f.autoAlpha&&(f.visibility=1)}for(b.className&&(c=this._classNamePT)&&(e=c.xfirst,e&&e._prev?this._linkCSSP(e._prev,c._next,e._prev._prev):e===this._firstPT&&(this._firstPT=c._next),c._next&&this._linkCSSP(c._next,c._next._next,e._prev),this._classNamePT=null),c=this._firstPT;c;)c.plugin&&c.plugin!==d&&c.plugin._kill&&(c.plugin._kill(b),d=c.plugin),c=c._next;return a.prototype._kill.call(this,f)};var Xa=function(a,b,c){var d,e,f,g;if(a.slice)for(e=a.length;--e>-1;)Xa(a[e],b,c);else for(d=a.childNodes,e=d.length;--e>-1;)f=d[e],g=f.type,f.style&&(b.push(ba(f)),c&&c.push(f)),1!==g&&9!==g&&11!==g||!f.childNodes.length||Xa(f,b,c)};return g.cascadeTo=function(a,c,d){var e,f,g,h,i=b.to(a,c,d),j=[i],k=[],l=[],m=[],n=b._internals.reservedProps;for(a=i._targets||i.target,Xa(a,k,m),i.render(c,!0,!0),Xa(a,l),i.render(0,!0,!0),i._enabled(!0),e=m.length;--e>-1;)if(f=ca(m[e],k[e],l[e]),f.firstMPT){f=f.difs;for(g in d)n[g]&&(f[g]=d[g]);h={};for(g in f)h[g]=k[e][g];j.push(b.fromTo(m[e],c,h,f))}return j},a.activate([g]),g},!0),function(){var a=_gsScope._gsDefine.plugin({propName:"roundProps",version:"1.6.0",priority:-1,API:2,init:function(a,b,c){return this._tween=c,!0}}),b=function(a){for(;a;)a.f||a.blob||(a.m=Math.round),a=a._next},c=a.prototype;c._onInitAllProps=function(){for(var a,c,d,e=this._tween,f=e.vars.roundProps.join?e.vars.roundProps:e.vars.roundProps.split(","),g=f.length,h={},i=e._propLookup.roundProps;--g>-1;)h[f[g]]=Math.round;for(g=f.length;--g>-1;)for(a=f[g],c=e._firstPT;c;)d=c._next,c.pg?c.t._mod(h):c.n===a&&(2===c.f&&c.t?b(c.t._firstPT):(this._add(c.t,a,c.s,c.c),d&&(d._prev=c._prev),c._prev?c._prev._next=d:e._firstPT===c&&(e._firstPT=d),c._next=c._prev=null,e._propLookup[a]=i)),c=d;return!1},c._add=function(a,b,c,d){this._addTween(a,b,c,c+d,b,Math.round),this._overwriteProps.push(b)}}(),function(){_gsScope._gsDefine.plugin({propName:"attr",API:2,version:"0.6.0",init:function(a,b,c,d){var e,f;if("function"!=typeof a.setAttribute)return!1;for(e in b)f=b[e],"function"==typeof f&&(f=f(d,a)),this._addTween(a,"setAttribute",a.getAttribute(e)+"",f+"",e,!1,e),this._overwriteProps.push(e);return!0}})}(),_gsScope._gsDefine.plugin({propName:"directionalRotation",version:"0.3.0",API:2,init:function(a,b,c,d){"object"!=typeof b&&(b={rotation:b}),this.finals={};var e,f,g,h,i,j,k=b.useRadians===!0?2*Math.PI:360,l=1e-6;for(e in b)"useRadians"!==e&&(h=b[e],"function"==typeof h&&(h=h(d,a)),j=(h+"").split("_"),f=j[0],g=parseFloat("function"!=typeof a[e]?a[e]:a[e.indexOf("set")||"function"!=typeof a["get"+e.substr(3)]?e:"get"+e.substr(3)]()),h=this.finals[e]="string"==typeof f&&"="===f.charAt(1)?g+parseInt(f.charAt(0)+"1",10)*Number(f.substr(2)):Number(f)||0,i=h-g,j.length&&(f=j.join("_"),-1!==f.indexOf("short")&&(i%=k,i!==i%(k/2)&&(i=0>i?i+k:i-k)),-1!==f.indexOf("_cw")&&0>i?i=(i+9999999999*k)%k-(i/k|0)*k:-1!==f.indexOf("ccw")&&i>0&&(i=(i-9999999999*k)%k-(i/k|0)*k)),(i>l||-l>i)&&(this._addTween(a,e,g,g+i,e),this._overwriteProps.push(e)));return!0},set:function(a){var b;if(1!==a)this._super.setRatio.call(this,a);else for(b=this._firstPT;b;)b.f?b.t[b.p](this.finals[b.p]):b.t[b.p]=this.finals[b.p],b=b._next}})._autoCSS=!0,_gsScope._gsDefine("easing.Back",["easing.Ease"],function(a){var b,c,d,e=_gsScope.GreenSockGlobals||_gsScope,f=e.com.greensock,g=2*Math.PI,h=Math.PI/2,i=f._class,j=function(b,c){var d=i("easing."+b,function(){},!0),e=d.prototype=new a;return e.constructor=d,e.getRatio=c,d},k=a.register||function(){},l=function(a,b,c,d,e){var f=i("easing."+a,{easeOut:new b,easeIn:new c,easeInOut:new d},!0);return k(f,a),f},m=function(a,b,c){this.t=a,this.v=b,c&&(this.next=c,c.prev=this,this.c=c.v-b,this.gap=c.t-a)},n=function(b,c){var d=i("easing."+b,function(a){this._p1=a||0===a?a:1.70158,this._p2=1.525*this._p1},!0),e=d.prototype=new a;return e.constructor=d,e.getRatio=c,e.config=function(a){return new d(a)},d},o=l("Back",n("BackOut",function(a){return(a-=1)*a*((this._p1+1)*a+this._p1)+1}),n("BackIn",function(a){return a*a*((this._p1+1)*a-this._p1)}),n("BackInOut",function(a){return(a*=2)<1?.5*a*a*((this._p2+1)*a-this._p2):.5*((a-=2)*a*((this._p2+1)*a+this._p2)+2)})),p=i("easing.SlowMo",function(a,b,c){b=b||0===b?b:.7,null==a?a=.7:a>1&&(a=1),this._p=1!==a?b:0,this._p1=(1-a)/2,this._p2=a,this._p3=this._p1+this._p2,this._calcEnd=c===!0},!0),q=p.prototype=new a;return q.constructor=p,q.getRatio=function(a){var b=a+(.5-a)*this._p;return a<this._p1?this._calcEnd?1-(a=1-a/this._p1)*a:b-(a=1-a/this._p1)*a*a*a*b:a>this._p3?this._calcEnd?1-(a=(a-this._p3)/this._p1)*a:b+(a-b)*(a=(a-this._p3)/this._p1)*a*a*a:this._calcEnd?1:b},p.ease=new p(.7,.7),q.config=p.config=function(a,b,c){return new p(a,b,c)},b=i("easing.SteppedEase",function(a){a=a||1,this._p1=1/a,this._p2=a+1},!0),q=b.prototype=new a,q.constructor=b,q.getRatio=function(a){return 0>a?a=0:a>=1&&(a=.999999999),(this._p2*a>>0)*this._p1},q.config=b.config=function(a){return new b(a)},c=i("easing.RoughEase",function(b){b=b||{};for(var c,d,e,f,g,h,i=b.taper||"none",j=[],k=0,l=0|(b.points||20),n=l,o=b.randomize!==!1,p=b.clamp===!0,q=b.template instanceof a?b.template:null,r="number"==typeof b.strength?.4*b.strength:.4;--n>-1;)c=o?Math.random():1/l*n,d=q?q.getRatio(c):c,"none"===i?e=r:"out"===i?(f=1-c,e=f*f*r):"in"===i?e=c*c*r:.5>c?(f=2*c,e=f*f*.5*r):(f=2*(1-c),e=f*f*.5*r),o?d+=Math.random()*e-.5*e:n%2?d+=.5*e:d-=.5*e,p&&(d>1?d=1:0>d&&(d=0)),j[k++]={x:c,y:d};for(j.sort(function(a,b){return a.x-b.x}),h=new m(1,1,null),n=l;--n>-1;)g=j[n],h=new m(g.x,g.y,h);this._prev=new m(0,0,0!==h.t?h:h.next)},!0),q=c.prototype=new a,q.constructor=c,q.getRatio=function(a){var b=this._prev;if(a>b.t){for(;b.next&&a>=b.t;)b=b.next;b=b.prev}else for(;b.prev&&a<=b.t;)b=b.prev;return this._prev=b,b.v+(a-b.t)/b.gap*b.c},q.config=function(a){return new c(a)},c.ease=new c,l("Bounce",j("BounceOut",function(a){return 1/2.75>a?7.5625*a*a:2/2.75>a?7.5625*(a-=1.5/2.75)*a+.75:2.5/2.75>a?7.5625*(a-=2.25/2.75)*a+.9375:7.5625*(a-=2.625/2.75)*a+.984375}),j("BounceIn",function(a){return(a=1-a)<1/2.75?1-7.5625*a*a:2/2.75>a?1-(7.5625*(a-=1.5/2.75)*a+.75):2.5/2.75>a?1-(7.5625*(a-=2.25/2.75)*a+.9375):1-(7.5625*(a-=2.625/2.75)*a+.984375)}),j("BounceInOut",function(a){var b=.5>a;return a=b?1-2*a:2*a-1,a=1/2.75>a?7.5625*a*a:2/2.75>a?7.5625*(a-=1.5/2.75)*a+.75:2.5/2.75>a?7.5625*(a-=2.25/2.75)*a+.9375:7.5625*(a-=2.625/2.75)*a+.984375,b?.5*(1-a):.5*a+.5})),l("Circ",j("CircOut",function(a){return Math.sqrt(1-(a-=1)*a)}),j("CircIn",function(a){return-(Math.sqrt(1-a*a)-1)}),j("CircInOut",function(a){return(a*=2)<1?-.5*(Math.sqrt(1-a*a)-1):.5*(Math.sqrt(1-(a-=2)*a)+1)})),d=function(b,c,d){var e=i("easing."+b,function(a,b){this._p1=a>=1?a:1,this._p2=(b||d)/(1>a?a:1),this._p3=this._p2/g*(Math.asin(1/this._p1)||0),this._p2=g/this._p2},!0),f=e.prototype=new a;return f.constructor=e,f.getRatio=c,f.config=function(a,b){return new e(a,b)},e},l("Elastic",d("ElasticOut",function(a){return this._p1*Math.pow(2,-10*a)*Math.sin((a-this._p3)*this._p2)+1},.3),d("ElasticIn",function(a){return-(this._p1*Math.pow(2,10*(a-=1))*Math.sin((a-this._p3)*this._p2))},.3),d("ElasticInOut",function(a){return(a*=2)<1?-.5*(this._p1*Math.pow(2,10*(a-=1))*Math.sin((a-this._p3)*this._p2)):this._p1*Math.pow(2,-10*(a-=1))*Math.sin((a-this._p3)*this._p2)*.5+1},.45)),l("Expo",j("ExpoOut",function(a){return 1-Math.pow(2,-10*a)}),j("ExpoIn",function(a){return Math.pow(2,10*(a-1))-.001}),j("ExpoInOut",function(a){return(a*=2)<1?.5*Math.pow(2,10*(a-1)):.5*(2-Math.pow(2,-10*(a-1)))})),l("Sine",j("SineOut",function(a){return Math.sin(a*h)}),j("SineIn",function(a){return-Math.cos(a*h)+1}),j("SineInOut",function(a){return-.5*(Math.cos(Math.PI*a)-1)})),i("easing.EaseLookup",{find:function(b){return a.map[b]}},!0),k(e.SlowMo,"SlowMo","ease,"),k(c,"RoughEase","ease,"),k(b,"SteppedEase","ease,"),o},!0)}),_gsScope._gsDefine&&_gsScope._gsQueue.pop()(),function(a,b){"use strict";var c={},d=a.GreenSockGlobals=a.GreenSockGlobals||a;if(!d.TweenLite){var e,f,g,h,i,j=function(a){var b,c=a.split("."),e=d;for(b=0;b<c.length;b++)e[c[b]]=e=e[c[b]]||{};return e},k=j("com.greensock"),l=1e-10,m=function(a){var b,c=[],d=a.length;for(b=0;b!==d;c.push(a[b++]));return c},n=function(){},o=function(){var a=Object.prototype.toString,b=a.call([]);return function(c){return null!=c&&(c instanceof Array||"object"==typeof c&&!!c.push&&a.call(c)===b)}}(),p={},q=function(e,f,g,h){this.sc=p[e]?p[e].sc:[],p[e]=this,this.gsClass=null,this.func=g;var i=[];this.check=function(k){for(var l,m,n,o,r,s=f.length,t=s;--s>-1;)(l=p[f[s]]||new q(f[s],[])).gsClass?(i[s]=l.gsClass,t--):k&&l.sc.push(this);if(0===t&&g){if(m=("com.greensock."+e).split("."),n=m.pop(),o=j(m.join("."))[n]=this.gsClass=g.apply(g,i),h)if(d[n]=c[n]=o,r="undefined"!=typeof module&&module.exports,!r&&"function"==typeof define&&define.amd)define((a.GreenSockAMDPath?a.GreenSockAMDPath+"/":"")+e.split(".").pop(),[],function(){return o});else if(r)if(e===b){module.exports=c[b]=o;for(s in c)o[s]=c[s]}else c[b]&&(c[b][n]=o);for(s=0;s<this.sc.length;s++)this.sc[s].check()}},this.check(!0)},r=a._gsDefine=function(a,b,c,d){return new q(a,b,c,d)},s=k._class=function(a,b,c){return b=b||function(){},r(a,[],function(){return b},c),b};r.globals=d;var t=[0,0,1,1],u=s("easing.Ease",function(a,b,c,d){this._func=a,this._type=c||0,this._power=d||0,this._params=b?t.concat(b):t},!0),v=u.map={},w=u.register=function(a,b,c,d){for(var e,f,g,h,i=b.split(","),j=i.length,l=(c||"easeIn,easeOut,easeInOut").split(",");--j>-1;)for(f=i[j],e=d?s("easing."+f,null,!0):k.easing[f]||{},g=l.length;--g>-1;)h=l[g],v[f+"."+h]=v[h+f]=e[h]=a.getRatio?a:a[h]||new a};for(g=u.prototype,g._calcEnd=!1,g.getRatio=function(a){if(this._func)return this._params[0]=a,this._func.apply(null,this._params);var b=this._type,c=this._power,d=1===b?1-a:2===b?a:.5>a?2*a:2*(1-a);return 1===c?d*=d:2===c?d*=d*d:3===c?d*=d*d*d:4===c&&(d*=d*d*d*d),1===b?1-d:2===b?d:.5>a?d/2:1-d/2},e=["Linear","Quad","Cubic","Quart","Quint,Strong"],f=e.length;--f>-1;)g=e[f]+",Power"+f,w(new u(null,null,1,f),g,"easeOut",!0),w(new u(null,null,2,f),g,"easeIn"+(0===f?",easeNone":"")),w(new u(null,null,3,f),g,"easeInOut");v.linear=k.easing.Linear.easeIn,v.swing=k.easing.Quad.easeInOut;var x=s("events.EventDispatcher",function(a){this._listeners={},this._eventTarget=a||this});g=x.prototype,g.addEventListener=function(a,b,c,d,e){e=e||0;var f,g,j=this._listeners[a],k=0;for(this!==h||i||h.wake(),null==j&&(this._listeners[a]=j=[]),g=j.length;--g>-1;)f=j[g],f.c===b&&f.s===c?j.splice(g,1):0===k&&f.pr<e&&(k=g+1);j.splice(k,0,{c:b,s:c,up:d,pr:e})},g.removeEventListener=function(a,b){var c,d=this._listeners[a];if(d)for(c=d.length;--c>-1;)if(d[c].c===b)return void d.splice(c,1)},g.dispatchEvent=function(a){var b,c,d,e=this._listeners[a];if(e)for(b=e.length,b>1&&(e=e.slice(0)),c=this._eventTarget;--b>-1;)d=e[b],d&&(d.up?d.c.call(d.s||c,{type:a,target:c}):d.c.call(d.s||c))};var y=a.requestAnimationFrame,z=a.cancelAnimationFrame,A=Date.now||function(){return(new Date).getTime()},B=A();for(e=["ms","moz","webkit","o"],f=e.length;--f>-1&&!y;)y=a[e[f]+"RequestAnimationFrame"],z=a[e[f]+"CancelAnimationFrame"]||a[e[f]+"CancelRequestAnimationFrame"];s("Ticker",function(a,b){var c,d,e,f,g,j=this,k=A(),m=b!==!1&&y?"auto":!1,o=500,p=33,q="tick",r=function(a){var b,h,i=A()-B;i>o&&(k+=i-p),B+=i,j.time=(B-k)/1e3,b=j.time-g,(!c||b>0||a===!0)&&(j.frame++,g+=b+(b>=f?.004:f-b),h=!0),a!==!0&&(e=d(r)),h&&j.dispatchEvent(q)};x.call(j),j.time=j.frame=0,j.tick=function(){r(!0)},j.lagSmoothing=function(a,b){o=a||1/l,p=Math.min(b,o,0)},j.sleep=function(){null!=e&&(m&&z?z(e):clearTimeout(e),d=n,e=null,j===h&&(i=!1))},j.wake=function(a){null!==e?j.sleep():a?k+=-B+(B=A()):j.frame>10&&(B=A()-o+5),d=0===c?n:m&&y?y:function(a){return setTimeout(a,1e3*(g-j.time)+1|0)},j===h&&(i=!0),r(2)},j.fps=function(a){return arguments.length?(c=a,f=1/(c||60),g=this.time+f,void j.wake()):c},j.useRAF=function(a){return arguments.length?(j.sleep(),m=a,void j.fps(c)):m},j.fps(a),setTimeout(function(){"auto"===m&&j.frame<5&&"hidden"!==document.visibilityState&&j.useRAF(!1)},1500)}),g=k.Ticker.prototype=new k.events.EventDispatcher,g.constructor=k.Ticker;var C=s("core.Animation",function(a,b){if(this.vars=b=b||{},this._duration=this._totalDuration=a||0,this._delay=Number(b.delay)||0,this._timeScale=1,this._active=b.immediateRender===!0,this.data=b.data,this._reversed=b.reversed===!0,V){i||h.wake();var c=this.vars.useFrames?U:V;c.add(this,c._time),this.vars.paused&&this.paused(!0)}});h=C.ticker=new k.Ticker,g=C.prototype,g._dirty=g._gc=g._initted=g._paused=!1,g._totalTime=g._time=0,g._rawPrevTime=-1,g._next=g._last=g._onUpdate=g._timeline=g.timeline=null,g._paused=!1;var D=function(){i&&A()-B>2e3&&h.wake(),setTimeout(D,2e3)};D(),g.play=function(a,b){return null!=a&&this.seek(a,b),this.reversed(!1).paused(!1)},g.pause=function(a,b){return null!=a&&this.seek(a,b),this.paused(!0)},g.resume=function(a,b){return null!=a&&this.seek(a,b),this.paused(!1)},g.seek=function(a,b){return this.totalTime(Number(a),b!==!1)},g.restart=function(a,b){return this.reversed(!1).paused(!1).totalTime(a?-this._delay:0,b!==!1,!0)},g.reverse=function(a,b){return null!=a&&this.seek(a||this.totalDuration(),b),this.reversed(!0).paused(!1)},g.render=function(a,b,c){},g.invalidate=function(){return this._time=this._totalTime=0,this._initted=this._gc=!1,this._rawPrevTime=-1,(this._gc||!this.timeline)&&this._enabled(!0),this},g.isActive=function(){var a,b=this._timeline,c=this._startTime;return!b||!this._gc&&!this._paused&&b.isActive()&&(a=b.rawTime())>=c&&a<c+this.totalDuration()/this._timeScale},g._enabled=function(a,b){return i||h.wake(),this._gc=!a,this._active=this.isActive(),b!==!0&&(a&&!this.timeline?this._timeline.add(this,this._startTime-this._delay):!a&&this.timeline&&this._timeline._remove(this,!0)),!1},g._kill=function(a,b){return this._enabled(!1,!1)},g.kill=function(a,b){return this._kill(a,b),this},g._uncache=function(a){for(var b=a?this:this.timeline;b;)b._dirty=!0,b=b.timeline;return this},g._swapSelfInParams=function(a){for(var b=a.length,c=a.concat();--b>-1;)"{self}"===a[b]&&(c[b]=this);return c},g._callback=function(a){var b=this.vars,c=b[a],d=b[a+"Params"],e=b[a+"Scope"]||b.callbackScope||this,f=d?d.length:0;switch(f){case 0:c.call(e);break;case 1:c.call(e,d[0]);break;case 2:c.call(e,d[0],d[1]);break;default:c.apply(e,d)}},g.eventCallback=function(a,b,c,d){if("on"===(a||"").substr(0,2)){var e=this.vars;if(1===arguments.length)return e[a];null==b?delete e[a]:(e[a]=b,e[a+"Params"]=o(c)&&-1!==c.join("").indexOf("{self}")?this._swapSelfInParams(c):c,e[a+"Scope"]=d),"onUpdate"===a&&(this._onUpdate=b)}return this},g.delay=function(a){return arguments.length?(this._timeline.smoothChildTiming&&this.startTime(this._startTime+a-this._delay),this._delay=a,this):this._delay},g.duration=function(a){return arguments.length?(this._duration=this._totalDuration=a,this._uncache(!0),this._timeline.smoothChildTiming&&this._time>0&&this._time<this._duration&&0!==a&&this.totalTime(this._totalTime*(a/this._duration),!0),this):(this._dirty=!1,this._duration)},g.totalDuration=function(a){return this._dirty=!1,arguments.length?this.duration(a):this._totalDuration},g.time=function(a,b){return arguments.length?(this._dirty&&this.totalDuration(),this.totalTime(a>this._duration?this._duration:a,b)):this._time},g.totalTime=function(a,b,c){if(i||h.wake(),!arguments.length)return this._totalTime;if(this._timeline){if(0>a&&!c&&(a+=this.totalDuration()),this._timeline.smoothChildTiming){this._dirty&&this.totalDuration();var d=this._totalDuration,e=this._timeline;if(a>d&&!c&&(a=d),this._startTime=(this._paused?this._pauseTime:e._time)-(this._reversed?d-a:a)/this._timeScale,e._dirty||this._uncache(!1),e._timeline)for(;e._timeline;)e._timeline._time!==(e._startTime+e._totalTime)/e._timeScale&&e.totalTime(e._totalTime,!0),e=e._timeline}this._gc&&this._enabled(!0,!1),(this._totalTime!==a||0===this._duration)&&(I.length&&X(),this.render(a,b,!1),I.length&&X())}return this},g.progress=g.totalProgress=function(a,b){var c=this.duration();return arguments.length?this.totalTime(c*a,b):c?this._time/c:this.ratio},g.startTime=function(a){return arguments.length?(a!==this._startTime&&(this._startTime=a,this.timeline&&this.timeline._sortChildren&&this.timeline.add(this,a-this._delay)),this):this._startTime},g.endTime=function(a){return this._startTime+(0!=a?this.totalDuration():this.duration())/this._timeScale},g.timeScale=function(a){if(!arguments.length)return this._timeScale;if(a=a||l,this._timeline&&this._timeline.smoothChildTiming){var b=this._pauseTime,c=b||0===b?b:this._timeline.totalTime();this._startTime=c-(c-this._startTime)*this._timeScale/a}return this._timeScale=a,this._uncache(!1)},g.reversed=function(a){return arguments.length?(a!=this._reversed&&(this._reversed=a,this.totalTime(this._timeline&&!this._timeline.smoothChildTiming?this.totalDuration()-this._totalTime:this._totalTime,!0)),this):this._reversed},g.paused=function(a){if(!arguments.length)return this._paused;var b,c,d=this._timeline;return a!=this._paused&&d&&(i||a||h.wake(),b=d.rawTime(),c=b-this._pauseTime,!a&&d.smoothChildTiming&&(this._startTime+=c,this._uncache(!1)),this._pauseTime=a?b:null,this._paused=a,this._active=this.isActive(),!a&&0!==c&&this._initted&&this.duration()&&(b=d.smoothChildTiming?this._totalTime:(b-this._startTime)/this._timeScale,this.render(b,b===this._totalTime,!0))),this._gc&&!a&&this._enabled(!0,!1),this};var E=s("core.SimpleTimeline",function(a){C.call(this,0,a),this.autoRemoveChildren=this.smoothChildTiming=!0});g=E.prototype=new C,g.constructor=E,g.kill()._gc=!1,g._first=g._last=g._recent=null,g._sortChildren=!1,g.add=g.insert=function(a,b,c,d){var e,f;if(a._startTime=Number(b||0)+a._delay,a._paused&&this!==a._timeline&&(a._pauseTime=a._startTime+(this.rawTime()-a._startTime)/a._timeScale),a.timeline&&a.timeline._remove(a,!0),a.timeline=a._timeline=this,a._gc&&a._enabled(!0,!0),e=this._last,this._sortChildren)for(f=a._startTime;e&&e._startTime>f;)e=e._prev;return e?(a._next=e._next,e._next=a):(a._next=this._first,this._first=a),a._next?a._next._prev=a:this._last=a,a._prev=e,this._recent=a,this._timeline&&this._uncache(!0),this},g._remove=function(a,b){return a.timeline===this&&(b||a._enabled(!1,!0),a._prev?a._prev._next=a._next:this._first===a&&(this._first=a._next),a._next?a._next._prev=a._prev:this._last===a&&(this._last=a._prev),a._next=a._prev=a.timeline=null,a===this._recent&&(this._recent=this._last),this._timeline&&this._uncache(!0)),this},g.render=function(a,b,c){var d,e=this._first;for(this._totalTime=this._time=this._rawPrevTime=a;e;)d=e._next,(e._active||a>=e._startTime&&!e._paused)&&(e._reversed?e.render((e._dirty?e.totalDuration():e._totalDuration)-(a-e._startTime)*e._timeScale,b,c):e.render((a-e._startTime)*e._timeScale,b,c)),e=d},g.rawTime=function(){return i||h.wake(),this._totalTime};var F=s("TweenLite",function(b,c,d){if(C.call(this,c,d),this.render=F.prototype.render,null==b)throw"Cannot tween a null target.";this.target=b="string"!=typeof b?b:F.selector(b)||b;var e,f,g,h=b.jquery||b.length&&b!==a&&b[0]&&(b[0]===a||b[0].nodeType&&b[0].style&&!b.nodeType),i=this.vars.overwrite;if(this._overwrite=i=null==i?T[F.defaultOverwrite]:"number"==typeof i?i>>0:T[i],(h||b instanceof Array||b.push&&o(b))&&"number"!=typeof b[0])for(this._targets=g=m(b),this._propLookup=[],this._siblings=[],e=0;e<g.length;e++)f=g[e],f?"string"!=typeof f?f.length&&f!==a&&f[0]&&(f[0]===a||f[0].nodeType&&f[0].style&&!f.nodeType)?(g.splice(e--,1),this._targets=g=g.concat(m(f))):(this._siblings[e]=Y(f,this,!1),1===i&&this._siblings[e].length>1&&$(f,this,null,1,this._siblings[e])):(f=g[e--]=F.selector(f),"string"==typeof f&&g.splice(e+1,1)):g.splice(e--,1);else this._propLookup={},this._siblings=Y(b,this,!1),1===i&&this._siblings.length>1&&$(b,this,null,1,this._siblings);(this.vars.immediateRender||0===c&&0===this._delay&&this.vars.immediateRender!==!1)&&(this._time=-l,this.render(Math.min(0,-this._delay)))},!0),G=function(b){return b&&b.length&&b!==a&&b[0]&&(b[0]===a||b[0].nodeType&&b[0].style&&!b.nodeType);
},H=function(a,b){var c,d={};for(c in a)S[c]||c in b&&"transform"!==c&&"x"!==c&&"y"!==c&&"width"!==c&&"height"!==c&&"className"!==c&&"border"!==c||!(!P[c]||P[c]&&P[c]._autoCSS)||(d[c]=a[c],delete a[c]);a.css=d};g=F.prototype=new C,g.constructor=F,g.kill()._gc=!1,g.ratio=0,g._firstPT=g._targets=g._overwrittenProps=g._startAt=null,g._notifyPluginsOfEnabled=g._lazy=!1,F.version="1.19.0",F.defaultEase=g._ease=new u(null,null,1,1),F.defaultOverwrite="auto",F.ticker=h,F.autoSleep=120,F.lagSmoothing=function(a,b){h.lagSmoothing(a,b)},F.selector=a.$||a.jQuery||function(b){var c=a.$||a.jQuery;return c?(F.selector=c,c(b)):"undefined"==typeof document?b:document.querySelectorAll?document.querySelectorAll(b):document.getElementById("#"===b.charAt(0)?b.substr(1):b)};var I=[],J={},K=/(?:(-|-=|\+=)?\d*\.?\d*(?:e[\-+]?\d+)?)[0-9]/gi,L=function(a){for(var b,c=this._firstPT,d=1e-6;c;)b=c.blob?a?this.join(""):this.start:c.c*a+c.s,c.m?b=c.m(b,this._target||c.t):d>b&&b>-d&&(b=0),c.f?c.fp?c.t[c.p](c.fp,b):c.t[c.p](b):c.t[c.p]=b,c=c._next},M=function(a,b,c,d){var e,f,g,h,i,j,k,l=[a,b],m=0,n="",o=0;for(l.start=a,c&&(c(l),a=l[0],b=l[1]),l.length=0,e=a.match(K)||[],f=b.match(K)||[],d&&(d._next=null,d.blob=1,l._firstPT=l._applyPT=d),i=f.length,h=0;i>h;h++)k=f[h],j=b.substr(m,b.indexOf(k,m)-m),n+=j||!h?j:",",m+=j.length,o?o=(o+1)%5:"rgba("===j.substr(-5)&&(o=1),k===e[h]||e.length<=h?n+=k:(n&&(l.push(n),n=""),g=parseFloat(e[h]),l.push(g),l._firstPT={_next:l._firstPT,t:l,p:l.length-1,s:g,c:("="===k.charAt(1)?parseInt(k.charAt(0)+"1",10)*parseFloat(k.substr(2)):parseFloat(k)-g)||0,f:0,m:o&&4>o?Math.round:0}),m+=k.length;return n+=b.substr(m),n&&l.push(n),l.setRatio=L,l},N=function(a,b,c,d,e,f,g,h,i){"function"==typeof d&&(d=d(i||0,a));var j,k,l="get"===c?a[b]:c,m=typeof a[b],n="string"==typeof d&&"="===d.charAt(1),o={t:a,p:b,s:l,f:"function"===m,pg:0,n:e||b,m:f?"function"==typeof f?f:Math.round:0,pr:0,c:n?parseInt(d.charAt(0)+"1",10)*parseFloat(d.substr(2)):parseFloat(d)-l||0};return"number"!==m&&("function"===m&&"get"===c&&(k=b.indexOf("set")||"function"!=typeof a["get"+b.substr(3)]?b:"get"+b.substr(3),o.s=l=g?a[k](g):a[k]()),"string"==typeof l&&(g||isNaN(l))?(o.fp=g,j=M(l,d,h||F.defaultStringFilter,o),o={t:j,p:"setRatio",s:0,c:1,f:2,pg:0,n:e||b,pr:0,m:0}):n||(o.s=parseFloat(l),o.c=parseFloat(d)-o.s||0)),o.c?((o._next=this._firstPT)&&(o._next._prev=o),this._firstPT=o,o):void 0},O=F._internals={isArray:o,isSelector:G,lazyTweens:I,blobDif:M},P=F._plugins={},Q=O.tweenLookup={},R=0,S=O.reservedProps={ease:1,delay:1,overwrite:1,onComplete:1,onCompleteParams:1,onCompleteScope:1,useFrames:1,runBackwards:1,startAt:1,onUpdate:1,onUpdateParams:1,onUpdateScope:1,onStart:1,onStartParams:1,onStartScope:1,onReverseComplete:1,onReverseCompleteParams:1,onReverseCompleteScope:1,onRepeat:1,onRepeatParams:1,onRepeatScope:1,easeParams:1,yoyo:1,immediateRender:1,repeat:1,repeatDelay:1,data:1,paused:1,reversed:1,autoCSS:1,lazy:1,onOverwrite:1,callbackScope:1,stringFilter:1,id:1},T={none:0,all:1,auto:2,concurrent:3,allOnStart:4,preexisting:5,"true":1,"false":0},U=C._rootFramesTimeline=new E,V=C._rootTimeline=new E,W=30,X=O.lazyRender=function(){var a,b=I.length;for(J={};--b>-1;)a=I[b],a&&a._lazy!==!1&&(a.render(a._lazy[0],a._lazy[1],!0),a._lazy=!1);I.length=0};V._startTime=h.time,U._startTime=h.frame,V._active=U._active=!0,setTimeout(X,1),C._updateRoot=F.render=function(){var a,b,c;if(I.length&&X(),V.render((h.time-V._startTime)*V._timeScale,!1,!1),U.render((h.frame-U._startTime)*U._timeScale,!1,!1),I.length&&X(),h.frame>=W){W=h.frame+(parseInt(F.autoSleep,10)||120);for(c in Q){for(b=Q[c].tweens,a=b.length;--a>-1;)b[a]._gc&&b.splice(a,1);0===b.length&&delete Q[c]}if(c=V._first,(!c||c._paused)&&F.autoSleep&&!U._first&&1===h._listeners.tick.length){for(;c&&c._paused;)c=c._next;c||h.sleep()}}},h.addEventListener("tick",C._updateRoot);var Y=function(a,b,c){var d,e,f=a._gsTweenID;if(Q[f||(a._gsTweenID=f="t"+R++)]||(Q[f]={target:a,tweens:[]}),b&&(d=Q[f].tweens,d[e=d.length]=b,c))for(;--e>-1;)d[e]===b&&d.splice(e,1);return Q[f].tweens},Z=function(a,b,c,d){var e,f,g=a.vars.onOverwrite;return g&&(e=g(a,b,c,d)),g=F.onOverwrite,g&&(f=g(a,b,c,d)),e!==!1&&f!==!1},$=function(a,b,c,d,e){var f,g,h,i;if(1===d||d>=4){for(i=e.length,f=0;i>f;f++)if((h=e[f])!==b)h._gc||h._kill(null,a,b)&&(g=!0);else if(5===d)break;return g}var j,k=b._startTime+l,m=[],n=0,o=0===b._duration;for(f=e.length;--f>-1;)(h=e[f])===b||h._gc||h._paused||(h._timeline!==b._timeline?(j=j||_(b,0,o),0===_(h,j,o)&&(m[n++]=h)):h._startTime<=k&&h._startTime+h.totalDuration()/h._timeScale>k&&((o||!h._initted)&&k-h._startTime<=2e-10||(m[n++]=h)));for(f=n;--f>-1;)if(h=m[f],2===d&&h._kill(c,a,b)&&(g=!0),2!==d||!h._firstPT&&h._initted){if(2!==d&&!Z(h,b))continue;h._enabled(!1,!1)&&(g=!0)}return g},_=function(a,b,c){for(var d=a._timeline,e=d._timeScale,f=a._startTime;d._timeline;){if(f+=d._startTime,e*=d._timeScale,d._paused)return-100;d=d._timeline}return f/=e,f>b?f-b:c&&f===b||!a._initted&&2*l>f-b?l:(f+=a.totalDuration()/a._timeScale/e)>b+l?0:f-b-l};g._init=function(){var a,b,c,d,e,f,g=this.vars,h=this._overwrittenProps,i=this._duration,j=!!g.immediateRender,k=g.ease;if(g.startAt){this._startAt&&(this._startAt.render(-1,!0),this._startAt.kill()),e={};for(d in g.startAt)e[d]=g.startAt[d];if(e.overwrite=!1,e.immediateRender=!0,e.lazy=j&&g.lazy!==!1,e.startAt=e.delay=null,this._startAt=F.to(this.target,0,e),j)if(this._time>0)this._startAt=null;else if(0!==i)return}else if(g.runBackwards&&0!==i)if(this._startAt)this._startAt.render(-1,!0),this._startAt.kill(),this._startAt=null;else{0!==this._time&&(j=!1),c={};for(d in g)S[d]&&"autoCSS"!==d||(c[d]=g[d]);if(c.overwrite=0,c.data="isFromStart",c.lazy=j&&g.lazy!==!1,c.immediateRender=j,this._startAt=F.to(this.target,0,c),j){if(0===this._time)return}else this._startAt._init(),this._startAt._enabled(!1),this.vars.immediateRender&&(this._startAt=null)}if(this._ease=k=k?k instanceof u?k:"function"==typeof k?new u(k,g.easeParams):v[k]||F.defaultEase:F.defaultEase,g.easeParams instanceof Array&&k.config&&(this._ease=k.config.apply(k,g.easeParams)),this._easeType=this._ease._type,this._easePower=this._ease._power,this._firstPT=null,this._targets)for(f=this._targets.length,a=0;f>a;a++)this._initProps(this._targets[a],this._propLookup[a]={},this._siblings[a],h?h[a]:null,a)&&(b=!0);else b=this._initProps(this.target,this._propLookup,this._siblings,h,0);if(b&&F._onPluginEvent("_onInitAllProps",this),h&&(this._firstPT||"function"!=typeof this.target&&this._enabled(!1,!1)),g.runBackwards)for(c=this._firstPT;c;)c.s+=c.c,c.c=-c.c,c=c._next;this._onUpdate=g.onUpdate,this._initted=!0},g._initProps=function(b,c,d,e,f){var g,h,i,j,k,l;if(null==b)return!1;J[b._gsTweenID]&&X(),this.vars.css||b.style&&b!==a&&b.nodeType&&P.css&&this.vars.autoCSS!==!1&&H(this.vars,b);for(g in this.vars)if(l=this.vars[g],S[g])l&&(l instanceof Array||l.push&&o(l))&&-1!==l.join("").indexOf("{self}")&&(this.vars[g]=l=this._swapSelfInParams(l,this));else if(P[g]&&(j=new P[g])._onInitTween(b,this.vars[g],this,f)){for(this._firstPT=k={_next:this._firstPT,t:j,p:"setRatio",s:0,c:1,f:1,n:g,pg:1,pr:j._priority,m:0},h=j._overwriteProps.length;--h>-1;)c[j._overwriteProps[h]]=this._firstPT;(j._priority||j._onInitAllProps)&&(i=!0),(j._onDisable||j._onEnable)&&(this._notifyPluginsOfEnabled=!0),k._next&&(k._next._prev=k)}else c[g]=N.call(this,b,g,"get",l,g,0,null,this.vars.stringFilter,f);return e&&this._kill(e,b)?this._initProps(b,c,d,e,f):this._overwrite>1&&this._firstPT&&d.length>1&&$(b,this,c,this._overwrite,d)?(this._kill(c,b),this._initProps(b,c,d,e,f)):(this._firstPT&&(this.vars.lazy!==!1&&this._duration||this.vars.lazy&&!this._duration)&&(J[b._gsTweenID]=!0),i)},g.render=function(a,b,c){var d,e,f,g,h=this._time,i=this._duration,j=this._rawPrevTime;if(a>=i-1e-7)this._totalTime=this._time=i,this.ratio=this._ease._calcEnd?this._ease.getRatio(1):1,this._reversed||(d=!0,e="onComplete",c=c||this._timeline.autoRemoveChildren),0===i&&(this._initted||!this.vars.lazy||c)&&(this._startTime===this._timeline._duration&&(a=0),(0>j||0>=a&&a>=-1e-7||j===l&&"isPause"!==this.data)&&j!==a&&(c=!0,j>l&&(e="onReverseComplete")),this._rawPrevTime=g=!b||a||j===a?a:l);else if(1e-7>a)this._totalTime=this._time=0,this.ratio=this._ease._calcEnd?this._ease.getRatio(0):0,(0!==h||0===i&&j>0)&&(e="onReverseComplete",d=this._reversed),0>a&&(this._active=!1,0===i&&(this._initted||!this.vars.lazy||c)&&(j>=0&&(j!==l||"isPause"!==this.data)&&(c=!0),this._rawPrevTime=g=!b||a||j===a?a:l)),this._initted||(c=!0);else if(this._totalTime=this._time=a,this._easeType){var k=a/i,m=this._easeType,n=this._easePower;(1===m||3===m&&k>=.5)&&(k=1-k),3===m&&(k*=2),1===n?k*=k:2===n?k*=k*k:3===n?k*=k*k*k:4===n&&(k*=k*k*k*k),1===m?this.ratio=1-k:2===m?this.ratio=k:.5>a/i?this.ratio=k/2:this.ratio=1-k/2}else this.ratio=this._ease.getRatio(a/i);if(this._time!==h||c){if(!this._initted){if(this._init(),!this._initted||this._gc)return;if(!c&&this._firstPT&&(this.vars.lazy!==!1&&this._duration||this.vars.lazy&&!this._duration))return this._time=this._totalTime=h,this._rawPrevTime=j,I.push(this),void(this._lazy=[a,b]);this._time&&!d?this.ratio=this._ease.getRatio(this._time/i):d&&this._ease._calcEnd&&(this.ratio=this._ease.getRatio(0===this._time?0:1))}for(this._lazy!==!1&&(this._lazy=!1),this._active||!this._paused&&this._time!==h&&a>=0&&(this._active=!0),0===h&&(this._startAt&&(a>=0?this._startAt.render(a,b,c):e||(e="_dummyGS")),this.vars.onStart&&(0!==this._time||0===i)&&(b||this._callback("onStart"))),f=this._firstPT;f;)f.f?f.t[f.p](f.c*this.ratio+f.s):f.t[f.p]=f.c*this.ratio+f.s,f=f._next;this._onUpdate&&(0>a&&this._startAt&&a!==-1e-4&&this._startAt.render(a,b,c),b||(this._time!==h||d||c)&&this._callback("onUpdate")),e&&(!this._gc||c)&&(0>a&&this._startAt&&!this._onUpdate&&a!==-1e-4&&this._startAt.render(a,b,c),d&&(this._timeline.autoRemoveChildren&&this._enabled(!1,!1),this._active=!1),!b&&this.vars[e]&&this._callback(e),0===i&&this._rawPrevTime===l&&g!==l&&(this._rawPrevTime=0))}},g._kill=function(a,b,c){if("all"===a&&(a=null),null==a&&(null==b||b===this.target))return this._lazy=!1,this._enabled(!1,!1);b="string"!=typeof b?b||this._targets||this.target:F.selector(b)||b;var d,e,f,g,h,i,j,k,l,m=c&&this._time&&c._startTime===this._startTime&&this._timeline===c._timeline;if((o(b)||G(b))&&"number"!=typeof b[0])for(d=b.length;--d>-1;)this._kill(a,b[d],c)&&(i=!0);else{if(this._targets){for(d=this._targets.length;--d>-1;)if(b===this._targets[d]){h=this._propLookup[d]||{},this._overwrittenProps=this._overwrittenProps||[],e=this._overwrittenProps[d]=a?this._overwrittenProps[d]||{}:"all";break}}else{if(b!==this.target)return!1;h=this._propLookup,e=this._overwrittenProps=a?this._overwrittenProps||{}:"all"}if(h){if(j=a||h,k=a!==e&&"all"!==e&&a!==h&&("object"!=typeof a||!a._tempKill),c&&(F.onOverwrite||this.vars.onOverwrite)){for(f in j)h[f]&&(l||(l=[]),l.push(f));if((l||!a)&&!Z(this,c,b,l))return!1}for(f in j)(g=h[f])&&(m&&(g.f?g.t[g.p](g.s):g.t[g.p]=g.s,i=!0),g.pg&&g.t._kill(j)&&(i=!0),g.pg&&0!==g.t._overwriteProps.length||(g._prev?g._prev._next=g._next:g===this._firstPT&&(this._firstPT=g._next),g._next&&(g._next._prev=g._prev),g._next=g._prev=null),delete h[f]),k&&(e[f]=1);!this._firstPT&&this._initted&&this._enabled(!1,!1)}}return i},g.invalidate=function(){return this._notifyPluginsOfEnabled&&F._onPluginEvent("_onDisable",this),this._firstPT=this._overwrittenProps=this._startAt=this._onUpdate=null,this._notifyPluginsOfEnabled=this._active=this._lazy=!1,this._propLookup=this._targets?{}:[],C.prototype.invalidate.call(this),this.vars.immediateRender&&(this._time=-l,this.render(Math.min(0,-this._delay))),this},g._enabled=function(a,b){if(i||h.wake(),a&&this._gc){var c,d=this._targets;if(d)for(c=d.length;--c>-1;)this._siblings[c]=Y(d[c],this,!0);else this._siblings=Y(this.target,this,!0)}return C.prototype._enabled.call(this,a,b),this._notifyPluginsOfEnabled&&this._firstPT?F._onPluginEvent(a?"_onEnable":"_onDisable",this):!1},F.to=function(a,b,c){return new F(a,b,c)},F.from=function(a,b,c){return c.runBackwards=!0,c.immediateRender=0!=c.immediateRender,new F(a,b,c)},F.fromTo=function(a,b,c,d){return d.startAt=c,d.immediateRender=0!=d.immediateRender&&0!=c.immediateRender,new F(a,b,d)},F.delayedCall=function(a,b,c,d,e){return new F(b,0,{delay:a,onComplete:b,onCompleteParams:c,callbackScope:d,onReverseComplete:b,onReverseCompleteParams:c,immediateRender:!1,lazy:!1,useFrames:e,overwrite:0})},F.set=function(a,b){return new F(a,0,b)},F.getTweensOf=function(a,b){if(null==a)return[];a="string"!=typeof a?a:F.selector(a)||a;var c,d,e,f;if((o(a)||G(a))&&"number"!=typeof a[0]){for(c=a.length,d=[];--c>-1;)d=d.concat(F.getTweensOf(a[c],b));for(c=d.length;--c>-1;)for(f=d[c],e=c;--e>-1;)f===d[e]&&d.splice(c,1)}else for(d=Y(a).concat(),c=d.length;--c>-1;)(d[c]._gc||b&&!d[c].isActive())&&d.splice(c,1);return d},F.killTweensOf=F.killDelayedCallsTo=function(a,b,c){"object"==typeof b&&(c=b,b=!1);for(var d=F.getTweensOf(a,b),e=d.length;--e>-1;)d[e]._kill(c,a)};var aa=s("plugins.TweenPlugin",function(a,b){this._overwriteProps=(a||"").split(","),this._propName=this._overwriteProps[0],this._priority=b||0,this._super=aa.prototype},!0);if(g=aa.prototype,aa.version="1.19.0",aa.API=2,g._firstPT=null,g._addTween=N,g.setRatio=L,g._kill=function(a){var b,c=this._overwriteProps,d=this._firstPT;if(null!=a[this._propName])this._overwriteProps=[];else for(b=c.length;--b>-1;)null!=a[c[b]]&&c.splice(b,1);for(;d;)null!=a[d.n]&&(d._next&&(d._next._prev=d._prev),d._prev?(d._prev._next=d._next,d._prev=null):this._firstPT===d&&(this._firstPT=d._next)),d=d._next;return!1},g._mod=g._roundProps=function(a){for(var b,c=this._firstPT;c;)b=a[this._propName]||null!=c.n&&a[c.n.split(this._propName+"_").join("")],b&&"function"==typeof b&&(2===c.f?c.t._applyPT.m=b:c.m=b),c=c._next},F._onPluginEvent=function(a,b){var c,d,e,f,g,h=b._firstPT;if("_onInitAllProps"===a){for(;h;){for(g=h._next,d=e;d&&d.pr>h.pr;)d=d._next;(h._prev=d?d._prev:f)?h._prev._next=h:e=h,(h._next=d)?d._prev=h:f=h,h=g}h=b._firstPT=e}for(;h;)h.pg&&"function"==typeof h.t[a]&&h.t[a]()&&(c=!0),h=h._next;return c},aa.activate=function(a){for(var b=a.length;--b>-1;)a[b].API===aa.API&&(P[(new a[b])._propName]=a[b]);return!0},r.plugin=function(a){if(!(a&&a.propName&&a.init&&a.API))throw"illegal plugin definition.";var b,c=a.propName,d=a.priority||0,e=a.overwriteProps,f={init:"_onInitTween",set:"setRatio",kill:"_kill",round:"_mod",mod:"_mod",initAll:"_onInitAllProps"},g=s("plugins."+c.charAt(0).toUpperCase()+c.substr(1)+"Plugin",function(){aa.call(this,c,d),this._overwriteProps=e||[]},a.global===!0),h=g.prototype=new aa(c);h.constructor=g,g.API=a.API;for(b in f)"function"==typeof a[b]&&(h[f[b]]=a[b]);return g.version=a.version,aa.activate([g]),g},e=a._gsQueue){for(f=0;f<e.length;f++)e[f]();for(g in p)p[g].func||a.console.log("GSAP encountered missing dependency: "+g)}i=!1}}("undefined"!=typeof module&&module.exports&&"undefined"!=typeof global?global:this||window,"TweenMax");;
/*!
 * VERSION: 1.8.0
 * DATE: 2016-07-09
 * UPDATES AND DOCS AT: http://greensock.com
 *
 * @license Copyright (c) 2008-2016, GreenSock. All rights reserved.
 * This work is subject to the terms at http://greensock.com/standard-license or for
 * Club GreenSock members, the software agreement that was issued with your membership.
 * 
 * @author: Jack Doyle, jack@greensock.com
 **/
var _gsScope="undefined"!=typeof module&&module.exports&&"undefined"!=typeof global?global:this||window;(_gsScope._gsQueue||(_gsScope._gsQueue=[])).push(function(){"use strict";var a=document.documentElement,b=window,c=function(c,d){var e="x"===d?"Width":"Height",f="scroll"+e,g="client"+e,h=document.body;return c===b||c===a||c===h?Math.max(a[f],h[f])-(b["inner"+e]||a[g]||h[g]):c[f]-c["offset"+e]},d=function(a){return"string"==typeof a&&(a=TweenLite.selector(a)),a.length&&a!==b&&a[0]&&a[0].style&&!a.nodeType&&(a=a[0]),a===b||a.nodeType&&a.style?a:null},e=function(c,d){var e="scroll"+("x"===d?"Left":"Top");return c===b&&(null!=c.pageXOffset?e="page"+d.toUpperCase()+"Offset":c=null!=a[e]?a:document.body),function(){return c[e]}},f=function(c,f){var g=d(c).getBoundingClientRect(),h=!f||f===b||f===document.body,i=(h?a:f).getBoundingClientRect(),j={x:g.left-i.left,y:g.top-i.top};return!h&&f&&(j.x+=e(f,"x")(),j.y+=e(f,"y")()),j},g=function(a,b,d){var e=typeof a;return"number"===e||"string"===e&&"="===a.charAt(1)?a:"max"===a?c(b,d):Math.min(c(b,d),f(a,b)[d])},h=_gsScope._gsDefine.plugin({propName:"scrollTo",API:2,version:"1.8.0",init:function(a,c,d){return this._wdw=a===b,this._target=a,this._tween=d,"object"!=typeof c?(c={y:c},"string"==typeof c.y&&"max"!==c.y&&"="!==c.y.charAt(1)&&(c.x=c.y)):c.nodeType&&(c={y:c,x:c}),this.vars=c,this._autoKill=c.autoKill!==!1,this.getX=e(a,"x"),this.getY=e(a,"y"),this.x=this.xPrev=this.getX(),this.y=this.yPrev=this.getY(),null!=c.x?(this._addTween(this,"x",this.x,g(c.x,a,"x")-(c.offsetX||0),"scrollTo_x",!0),this._overwriteProps.push("scrollTo_x")):this.skipX=!0,null!=c.y?(this._addTween(this,"y",this.y,g(c.y,a,"y")-(c.offsetY||0),"scrollTo_y",!0),this._overwriteProps.push("scrollTo_y")):this.skipY=!0,!0},set:function(a){this._super.setRatio.call(this,a);var d=this._wdw||!this.skipX?this.getX():this.xPrev,e=this._wdw||!this.skipY?this.getY():this.yPrev,f=e-this.yPrev,g=d-this.xPrev,i=h.autoKillThreshold;this.x<0&&(this.x=0),this.y<0&&(this.y=0),this._autoKill&&(!this.skipX&&(g>i||-i>g)&&d<c(this._target,"x")&&(this.skipX=!0),!this.skipY&&(f>i||-i>f)&&e<c(this._target,"y")&&(this.skipY=!0),this.skipX&&this.skipY&&(this._tween.kill(),this.vars.onAutoKill&&this.vars.onAutoKill.apply(this.vars.onAutoKillScope||this._tween,this.vars.onAutoKillParams||[]))),this._wdw?b.scrollTo(this.skipX?d:this.x,this.skipY?e:this.y):(this.skipY||(this._target.scrollTop=this.y),this.skipX||(this._target.scrollLeft=this.x)),this.xPrev=this.x,this.yPrev=this.y}}),i=h.prototype;h.max=c,h.getOffset=f,h.autoKillThreshold=7,i._kill=function(a){return a.scrollTo_x&&(this.skipX=!0),a.scrollTo_y&&(this.skipY=!0),this._super._kill.call(this,a)}}),_gsScope._gsDefine&&_gsScope._gsQueue.pop()(),function(a){"use strict";var b=function(){return(_gsScope.GreenSockGlobals||_gsScope)[a]};"function"==typeof define&&define.amd?define(["TweenLite"],b):"undefined"!=typeof module&&module.exports&&(require("../TweenLite.js"),module.exports=b())}("ScrollToPlugin");;
!function(a){function b(b){var c=a(this),d=null,e=[],f=null,g=null,h=a.extend({rowSelector:"> li",submenuSelector:"*",submenuDirection:"right",tolerance:75,enter:a.noop,exit:a.noop,activate:a.noop,deactivate:a.noop,exitMenu:a.noop},b),i=3,j=300,k=function(a){e.push({x:a.pageX,y:a.pageY}),e.length>i&&e.shift()},l=function(){g&&clearTimeout(g),h.exitMenu(this)&&(d&&h.deactivate(d),d=null)},m=function(){g&&clearTimeout(g),h.enter(this),q(this)},n=function(){h.exit(this)},o=function(){p(this)},p=function(a){a!=d&&(d&&h.deactivate(d),h.activate(a),d=a)},q=function(a){var b=r();b?g=setTimeout(function(){q(a)},b):p(a)},r=function(){function o(a,b){return(b.y-a.y)/(b.x-a.x)}if(!d||!a(d).is(h.submenuSelector))return 0;var b=c.offset(),g={x:b.left,y:b.top-h.tolerance},i={x:b.left+c.outerWidth(),y:g.y},k={x:b.left,y:b.top+c.outerHeight()+h.tolerance},l={x:b.left+c.outerWidth(),y:k.y},m=e[e.length-1],n=e[0];if(!m)return 0;if(n||(n=m),n.x<b.left||n.x>l.x||n.y<b.top||n.y>l.y)return 0;if(f&&m.x==f.x&&m.y==f.y)return 0;var p=i,q=l;"left"==h.submenuDirection?(p=k,q=g):"below"==h.submenuDirection?(p=l,q=k):"above"==h.submenuDirection&&(p=g,q=i);var r=o(m,p),s=o(m,q),t=o(n,p),u=o(n,q);return r<t&&s>u?(f=m,j):(f=null,0)};c.mouseleave(l).find(h.rowSelector).mouseenter(m).mouseleave(n).click(o),a(document).mousemove(k)}a.fn.menuAim=function(a){return this.each(function(){b.call(this,a)}),this}}(jQuery);;
/*
 *  Remodal - v1.1.0
 *  Responsive, lightweight, fast, synchronized with CSS animations, fully customizable modal window plugin with declarative configuration and hash tracking.
 *  http://vodkabears.github.io/remodal/
 *
 *  Made by Ilya Makarov
 *  Under MIT License
 */

!function(a,b){"function"==typeof define&&define.amd?define(["jquery"],function(c){return b(a,c)}):"object"==typeof exports?b(a,require("jquery")):b(a,a.jQuery||a.Zepto)}(this,function(a,b){"use strict";function c(a){if(w&&"none"===a.css("animation-name")&&"none"===a.css("-webkit-animation-name")&&"none"===a.css("-moz-animation-name")&&"none"===a.css("-o-animation-name")&&"none"===a.css("-ms-animation-name"))return 0;var b,c,d,e,f=a.css("animation-duration")||a.css("-webkit-animation-duration")||a.css("-moz-animation-duration")||a.css("-o-animation-duration")||a.css("-ms-animation-duration")||"0s",g=a.css("animation-delay")||a.css("-webkit-animation-delay")||a.css("-moz-animation-delay")||a.css("-o-animation-delay")||a.css("-ms-animation-delay")||"0s",h=a.css("animation-iteration-count")||a.css("-webkit-animation-iteration-count")||a.css("-moz-animation-iteration-count")||a.css("-o-animation-iteration-count")||a.css("-ms-animation-iteration-count")||"1";for(f=f.split(", "),g=g.split(", "),h=h.split(", "),e=0,c=f.length,b=Number.NEGATIVE_INFINITY;e<c;e++)d=parseFloat(f[e])*parseInt(h[e],10)+parseFloat(g[e]),d>b&&(b=d);return b}function d(){if(b(document.body).height()<=b(window).height())return 0;var a,c,d=document.createElement("div"),e=document.createElement("div");return d.style.visibility="hidden",d.style.width="100px",document.body.appendChild(d),a=d.offsetWidth,d.style.overflow="scroll",e.style.width="100%",d.appendChild(e),c=e.offsetWidth,d.parentNode.removeChild(d),a-c}function e(){if(!x){var a,c,e=b("html"),f=k("is-locked");e.hasClass(f)||(c=b(document.body),a=parseInt(c.css("padding-right"),10)+d(),c.css("padding-right",a+"px"),e.addClass(f))}}function f(){if(!x){var a,c,e=b("html"),f=k("is-locked");e.hasClass(f)&&(c=b(document.body),a=parseInt(c.css("padding-right"),10)-d(),c.css("padding-right",a+"px"),e.removeClass(f))}}function g(a,b,c,d){var e=k("is",b),f=[k("is",u.CLOSING),k("is",u.OPENING),k("is",u.CLOSED),k("is",u.OPENED)].join(" ");a.$bg.removeClass(f).addClass(e),a.$overlay.removeClass(f).addClass(e),a.$wrapper.removeClass(f).addClass(e),a.$modal.removeClass(f).addClass(e),a.state=b,!c&&a.$modal.trigger({type:b,reason:d},[{reason:d}])}function h(a,d,e){var f=0,g=function(a){a.target===this&&f++},h=function(a){a.target===this&&0===--f&&(b.each(["$bg","$overlay","$wrapper","$modal"],function(a,b){e[b].off(r+" "+s)}),d())};b.each(["$bg","$overlay","$wrapper","$modal"],function(a,b){e[b].on(r,g).on(s,h)}),a(),0===c(e.$bg)&&0===c(e.$overlay)&&0===c(e.$wrapper)&&0===c(e.$modal)&&(b.each(["$bg","$overlay","$wrapper","$modal"],function(a,b){e[b].off(r+" "+s)}),d())}function i(a){a.state!==u.CLOSED&&(b.each(["$bg","$overlay","$wrapper","$modal"],function(b,c){a[c].off(r+" "+s)}),a.$bg.removeClass(a.settings.modifier),a.$overlay.removeClass(a.settings.modifier).hide(),a.$wrapper.hide(),f(),g(a,u.CLOSED,!0))}function j(a){var b,c,d,e,f={};for(a=a.replace(/\s*:\s*/g,":").replace(/\s*,\s*/g,","),b=a.split(","),e=0,c=b.length;e<c;e++)b[e]=b[e].split(":"),d=b[e][1],("string"==typeof d||d instanceof String)&&(d="true"===d||"false"!==d&&d),("string"==typeof d||d instanceof String)&&(d=isNaN(d)?d:+d),f[b[e][0]]=d;return f}function k(){for(var a=q,b=0;b<arguments.length;++b)a+="-"+arguments[b];return a}function l(){var a,c,d=location.hash.replace("#","");if(d){try{c=b('[data-remodal-id="'+d+'"]')}catch(e){}c&&c.length&&(a=b[p].lookup[c.data(p)],a&&a.settings.hashTracking&&a.open())}else n&&n.state===u.OPENED&&n.settings.hashTracking&&n.close()}function m(a,c){var d=b(document.body),e=d,f=this;f.settings=b.extend({},t,c),f.index=b[p].lookup.push(f)-1,f.state=u.CLOSED,f.$overlay=b("."+k("overlay")),null!==f.settings.appendTo&&f.settings.appendTo.length&&(e=b(f.settings.appendTo)),f.$overlay.length||(f.$overlay=b("<div>").addClass(k("overlay")+" "+k("is",u.CLOSED)).hide(),e.append(f.$overlay)),f.$bg=b("."+k("bg")).addClass(k("is",u.CLOSED)),f.$modal=a.addClass(q+" "+k("is-initialized")+" "+f.settings.modifier+" "+k("is",u.CLOSED)).attr("tabindex","-1"),f.$wrapper=b("<div>").addClass(k("wrapper")+" "+f.settings.modifier+" "+k("is",u.CLOSED)).hide().append(f.$modal),e.append(f.$wrapper),f.$wrapper.on("click."+q,'[data-remodal-action="close"]',function(a){a.preventDefault(),f.close()}),f.$wrapper.on("click."+q,'[data-remodal-action="cancel"]',function(a){a.preventDefault(),f.$modal.trigger(v.CANCELLATION),f.settings.closeOnCancel&&f.close(v.CANCELLATION)}),f.$wrapper.on("click."+q,'[data-remodal-action="confirm"]',function(a){a.preventDefault(),f.$modal.trigger(v.CONFIRMATION),f.settings.closeOnConfirm&&f.close(v.CONFIRMATION)}),f.$wrapper.on("click."+q,function(a){var c=b(a.target);c.hasClass(k("wrapper"))&&f.settings.closeOnOutsideClick&&f.close()})}var n,o,p="remodal",q=a.REMODAL_GLOBALS&&a.REMODAL_GLOBALS.NAMESPACE||p,r=b.map(["animationstart","webkitAnimationStart","MSAnimationStart","oAnimationStart"],function(a){return a+"."+q}).join(" "),s=b.map(["animationend","webkitAnimationEnd","MSAnimationEnd","oAnimationEnd"],function(a){return a+"."+q}).join(" "),t=b.extend({hashTracking:!0,closeOnConfirm:!0,closeOnCancel:!0,closeOnEscape:!0,closeOnOutsideClick:!0,modifier:"",appendTo:null},a.REMODAL_GLOBALS&&a.REMODAL_GLOBALS.DEFAULTS),u={CLOSING:"closing",CLOSED:"closed",OPENING:"opening",OPENED:"opened"},v={CONFIRMATION:"confirmation",CANCELLATION:"cancellation"},w=function(){var a=document.createElement("div").style;return void 0!==a.animationName||void 0!==a.WebkitAnimationName||void 0!==a.MozAnimationName||void 0!==a.msAnimationName||void 0!==a.OAnimationName}(),x=/iPad|iPhone|iPod/.test(navigator.platform);m.prototype.open=function(){var a,c=this;c.state!==u.OPENING&&c.state!==u.CLOSING&&(a=c.$modal.attr("data-remodal-id"),a&&c.settings.hashTracking&&(o=b(window).scrollTop(),location.hash=a),n&&n!==c&&i(n),n=c,e(),c.$bg.addClass(c.settings.modifier),c.$overlay.addClass(c.settings.modifier).show(),c.$wrapper.show().scrollTop(0),c.$modal.focus(),h(function(){g(c,u.OPENING)},function(){g(c,u.OPENED)},c))},m.prototype.close=function(a){var c=this;c.state!==u.OPENING&&c.state!==u.CLOSING&&(c.settings.hashTracking&&c.$modal.attr("data-remodal-id")===location.hash.substr(1)&&(location.hash="",b(window).scrollTop(o)),h(function(){g(c,u.CLOSING,!1,a)},function(){c.$bg.removeClass(c.settings.modifier),c.$overlay.removeClass(c.settings.modifier).hide(),c.$wrapper.hide(),f(),g(c,u.CLOSED,!1,a)},c))},m.prototype.getState=function(){return this.state},m.prototype.destroy=function(){var a,c=b[p].lookup;i(this),this.$wrapper.remove(),delete c[this.index],a=b.grep(c,function(a){return!!a}).length,0===a&&(this.$overlay.remove(),this.$bg.removeClass(k("is",u.CLOSING)+" "+k("is",u.OPENING)+" "+k("is",u.CLOSED)+" "+k("is",u.OPENED)))},b[p]={lookup:[]},b.fn[p]=function(a){var c,d;return this.each(function(e,f){d=b(f),null==d.data(p)?(c=new m(d,a),d.data(p,c.index),c.settings.hashTracking&&d.attr("data-remodal-id")===location.hash.substr(1)&&c.open()):c=b[p].lookup[d.data(p)]}),c},b(document).ready(function(){b(document).on("click","[data-remodal-target]",function(a){a.preventDefault();var c=a.currentTarget,d=c.getAttribute("data-remodal-target"),e=b('[data-remodal-id="'+d+'"]');b[p].lookup[e.data(p)].open()}),b(document).find("."+q).each(function(a,c){var d=b(c),e=d.data("remodal-options");e?("string"==typeof e||e instanceof String)&&(e=j(e)):e={},d[p](e)}),b(document).on("keydown."+q,function(a){n&&n.settings.closeOnEscape&&n.state===u.OPENED&&27===a.keyCode&&n.close()}),b(window).on("hashchange."+q,l)})});;
//! moment.js
//! version : 2.15.2
//! authors : Tim Wood, Iskren Chernev, Moment.js contributors
//! license : MIT
//! momentjs.com

;(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
    typeof define === 'function' && define.amd ? define(factory) :
    global.moment = factory()
}(this, function () { 'use strict';

    var hookCallback;

    function utils_hooks__hooks () {
        return hookCallback.apply(null, arguments);
    }

    // This is done to register the method called with moment()
    // without creating circular dependencies.
    function setHookCallback (callback) {
        hookCallback = callback;
    }

    function isArray(input) {
        return input instanceof Array || Object.prototype.toString.call(input) === '[object Array]';
    }

    function isObject(input) {
        // IE8 will treat undefined and null as object if it wasn't for
        // input != null
        return input != null && Object.prototype.toString.call(input) === '[object Object]';
    }

    function isObjectEmpty(obj) {
        var k;
        for (k in obj) {
            // even if its not own property I'd still call it non-empty
            return false;
        }
        return true;
    }

    function isDate(input) {
        return input instanceof Date || Object.prototype.toString.call(input) === '[object Date]';
    }

    function map(arr, fn) {
        var res = [], i;
        for (i = 0; i < arr.length; ++i) {
            res.push(fn(arr[i], i));
        }
        return res;
    }

    function hasOwnProp(a, b) {
        return Object.prototype.hasOwnProperty.call(a, b);
    }

    function extend(a, b) {
        for (var i in b) {
            if (hasOwnProp(b, i)) {
                a[i] = b[i];
            }
        }

        if (hasOwnProp(b, 'toString')) {
            a.toString = b.toString;
        }

        if (hasOwnProp(b, 'valueOf')) {
            a.valueOf = b.valueOf;
        }

        return a;
    }

    function create_utc__createUTC (input, format, locale, strict) {
        return createLocalOrUTC(input, format, locale, strict, true).utc();
    }

    function defaultParsingFlags() {
        // We need to deep clone this object.
        return {
            empty           : false,
            unusedTokens    : [],
            unusedInput     : [],
            overflow        : -2,
            charsLeftOver   : 0,
            nullInput       : false,
            invalidMonth    : null,
            invalidFormat   : false,
            userInvalidated : false,
            iso             : false,
            parsedDateParts : [],
            meridiem        : null
        };
    }

    function getParsingFlags(m) {
        if (m._pf == null) {
            m._pf = defaultParsingFlags();
        }
        return m._pf;
    }

    var some;
    if (Array.prototype.some) {
        some = Array.prototype.some;
    } else {
        some = function (fun) {
            var t = Object(this);
            var len = t.length >>> 0;

            for (var i = 0; i < len; i++) {
                if (i in t && fun.call(this, t[i], i, t)) {
                    return true;
                }
            }

            return false;
        };
    }

    function valid__isValid(m) {
        if (m._isValid == null) {
            var flags = getParsingFlags(m);
            var parsedParts = some.call(flags.parsedDateParts, function (i) {
                return i != null;
            });
            var isNowValid = !isNaN(m._d.getTime()) &&
                flags.overflow < 0 &&
                !flags.empty &&
                !flags.invalidMonth &&
                !flags.invalidWeekday &&
                !flags.nullInput &&
                !flags.invalidFormat &&
                !flags.userInvalidated &&
                (!flags.meridiem || (flags.meridiem && parsedParts));

            if (m._strict) {
                isNowValid = isNowValid &&
                    flags.charsLeftOver === 0 &&
                    flags.unusedTokens.length === 0 &&
                    flags.bigHour === undefined;
            }

            if (Object.isFrozen == null || !Object.isFrozen(m)) {
                m._isValid = isNowValid;
            }
            else {
                return isNowValid;
            }
        }
        return m._isValid;
    }

    function valid__createInvalid (flags) {
        var m = create_utc__createUTC(NaN);
        if (flags != null) {
            extend(getParsingFlags(m), flags);
        }
        else {
            getParsingFlags(m).userInvalidated = true;
        }

        return m;
    }

    function isUndefined(input) {
        return input === void 0;
    }

    // Plugins that add properties should also add the key here (null value),
    // so we can properly clone ourselves.
    var momentProperties = utils_hooks__hooks.momentProperties = [];

    function copyConfig(to, from) {
        var i, prop, val;

        if (!isUndefined(from._isAMomentObject)) {
            to._isAMomentObject = from._isAMomentObject;
        }
        if (!isUndefined(from._i)) {
            to._i = from._i;
        }
        if (!isUndefined(from._f)) {
            to._f = from._f;
        }
        if (!isUndefined(from._l)) {
            to._l = from._l;
        }
        if (!isUndefined(from._strict)) {
            to._strict = from._strict;
        }
        if (!isUndefined(from._tzm)) {
            to._tzm = from._tzm;
        }
        if (!isUndefined(from._isUTC)) {
            to._isUTC = from._isUTC;
        }
        if (!isUndefined(from._offset)) {
            to._offset = from._offset;
        }
        if (!isUndefined(from._pf)) {
            to._pf = getParsingFlags(from);
        }
        if (!isUndefined(from._locale)) {
            to._locale = from._locale;
        }

        if (momentProperties.length > 0) {
            for (i in momentProperties) {
                prop = momentProperties[i];
                val = from[prop];
                if (!isUndefined(val)) {
                    to[prop] = val;
                }
            }
        }

        return to;
    }

    var updateInProgress = false;

    // Moment prototype object
    function Moment(config) {
        copyConfig(this, config);
        this._d = new Date(config._d != null ? config._d.getTime() : NaN);
        // Prevent infinite loop in case updateOffset creates new moment
        // objects.
        if (updateInProgress === false) {
            updateInProgress = true;
            utils_hooks__hooks.updateOffset(this);
            updateInProgress = false;
        }
    }

    function isMoment (obj) {
        return obj instanceof Moment || (obj != null && obj._isAMomentObject != null);
    }

    function absFloor (number) {
        if (number < 0) {
            // -0 -> 0
            return Math.ceil(number) || 0;
        } else {
            return Math.floor(number);
        }
    }

    function toInt(argumentForCoercion) {
        var coercedNumber = +argumentForCoercion,
            value = 0;

        if (coercedNumber !== 0 && isFinite(coercedNumber)) {
            value = absFloor(coercedNumber);
        }

        return value;
    }

    // compare two arrays, return the number of differences
    function compareArrays(array1, array2, dontConvert) {
        var len = Math.min(array1.length, array2.length),
            lengthDiff = Math.abs(array1.length - array2.length),
            diffs = 0,
            i;
        for (i = 0; i < len; i++) {
            if ((dontConvert && array1[i] !== array2[i]) ||
                (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
                diffs++;
            }
        }
        return diffs + lengthDiff;
    }

    function warn(msg) {
        if (utils_hooks__hooks.suppressDeprecationWarnings === false &&
                (typeof console !==  'undefined') && console.warn) {
            console.warn('Deprecation warning: ' + msg);
        }
    }

    function deprecate(msg, fn) {
        var firstTime = true;

        return extend(function () {
            if (utils_hooks__hooks.deprecationHandler != null) {
                utils_hooks__hooks.deprecationHandler(null, msg);
            }
            if (firstTime) {
                var args = [];
                var arg;
                for (var i = 0; i < arguments.length; i++) {
                    arg = '';
                    if (typeof arguments[i] === 'object') {
                        arg += '\n[' + i + '] ';
                        for (var key in arguments[0]) {
                            arg += key + ': ' + arguments[0][key] + ', ';
                        }
                        arg = arg.slice(0, -2); // Remove trailing comma and space
                    } else {
                        arg = arguments[i];
                    }
                    args.push(arg);
                }
                warn(msg + '\nArguments: ' + Array.prototype.slice.call(args).join('') + '\n' + (new Error()).stack);
                firstTime = false;
            }
            return fn.apply(this, arguments);
        }, fn);
    }

    var deprecations = {};

    function deprecateSimple(name, msg) {
        if (utils_hooks__hooks.deprecationHandler != null) {
            utils_hooks__hooks.deprecationHandler(name, msg);
        }
        if (!deprecations[name]) {
            warn(msg);
            deprecations[name] = true;
        }
    }

    utils_hooks__hooks.suppressDeprecationWarnings = false;
    utils_hooks__hooks.deprecationHandler = null;

    function isFunction(input) {
        return input instanceof Function || Object.prototype.toString.call(input) === '[object Function]';
    }

    function locale_set__set (config) {
        var prop, i;
        for (i in config) {
            prop = config[i];
            if (isFunction(prop)) {
                this[i] = prop;
            } else {
                this['_' + i] = prop;
            }
        }
        this._config = config;
        // Lenient ordinal parsing accepts just a number in addition to
        // number + (possibly) stuff coming from _ordinalParseLenient.
        this._ordinalParseLenient = new RegExp(this._ordinalParse.source + '|' + (/\d{1,2}/).source);
    }

    function mergeConfigs(parentConfig, childConfig) {
        var res = extend({}, parentConfig), prop;
        for (prop in childConfig) {
            if (hasOwnProp(childConfig, prop)) {
                if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) {
                    res[prop] = {};
                    extend(res[prop], parentConfig[prop]);
                    extend(res[prop], childConfig[prop]);
                } else if (childConfig[prop] != null) {
                    res[prop] = childConfig[prop];
                } else {
                    delete res[prop];
                }
            }
        }
        for (prop in parentConfig) {
            if (hasOwnProp(parentConfig, prop) &&
                    !hasOwnProp(childConfig, prop) &&
                    isObject(parentConfig[prop])) {
                // make sure changes to properties don't modify parent config
                res[prop] = extend({}, res[prop]);
            }
        }
        return res;
    }

    function Locale(config) {
        if (config != null) {
            this.set(config);
        }
    }

    var keys;

    if (Object.keys) {
        keys = Object.keys;
    } else {
        keys = function (obj) {
            var i, res = [];
            for (i in obj) {
                if (hasOwnProp(obj, i)) {
                    res.push(i);
                }
            }
            return res;
        };
    }

    var defaultCalendar = {
        sameDay : '[Today at] LT',
        nextDay : '[Tomorrow at] LT',
        nextWeek : 'dddd [at] LT',
        lastDay : '[Yesterday at] LT',
        lastWeek : '[Last] dddd [at] LT',
        sameElse : 'L'
    };

    function locale_calendar__calendar (key, mom, now) {
        var output = this._calendar[key] || this._calendar['sameElse'];
        return isFunction(output) ? output.call(mom, now) : output;
    }

    var defaultLongDateFormat = {
        LTS  : 'h:mm:ss A',
        LT   : 'h:mm A',
        L    : 'MM/DD/YYYY',
        LL   : 'MMMM D, YYYY',
        LLL  : 'MMMM D, YYYY h:mm A',
        LLLL : 'dddd, MMMM D, YYYY h:mm A'
    };

    function longDateFormat (key) {
        var format = this._longDateFormat[key],
            formatUpper = this._longDateFormat[key.toUpperCase()];

        if (format || !formatUpper) {
            return format;
        }

        this._longDateFormat[key] = formatUpper.replace(/MMMM|MM|DD|dddd/g, function (val) {
            return val.slice(1);
        });

        return this._longDateFormat[key];
    }

    var defaultInvalidDate = 'Invalid date';

    function invalidDate () {
        return this._invalidDate;
    }

    var defaultOrdinal = '%d';
    var defaultOrdinalParse = /\d{1,2}/;

    function ordinal (number) {
        return this._ordinal.replace('%d', number);
    }

    var defaultRelativeTime = {
        future : 'in %s',
        past   : '%s ago',
        s  : 'a few seconds',
        m  : 'a minute',
        mm : '%d minutes',
        h  : 'an hour',
        hh : '%d hours',
        d  : 'a day',
        dd : '%d days',
        M  : 'a month',
        MM : '%d months',
        y  : 'a year',
        yy : '%d years'
    };

    function relative__relativeTime (number, withoutSuffix, string, isFuture) {
        var output = this._relativeTime[string];
        return (isFunction(output)) ?
            output(number, withoutSuffix, string, isFuture) :
            output.replace(/%d/i, number);
    }

    function pastFuture (diff, output) {
        var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
        return isFunction(format) ? format(output) : format.replace(/%s/i, output);
    }

    var aliases = {};

    function addUnitAlias (unit, shorthand) {
        var lowerCase = unit.toLowerCase();
        aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit;
    }

    function normalizeUnits(units) {
        return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined;
    }

    function normalizeObjectUnits(inputObject) {
        var normalizedInput = {},
            normalizedProp,
            prop;

        for (prop in inputObject) {
            if (hasOwnProp(inputObject, prop)) {
                normalizedProp = normalizeUnits(prop);
                if (normalizedProp) {
                    normalizedInput[normalizedProp] = inputObject[prop];
                }
            }
        }

        return normalizedInput;
    }

    var priorities = {};

    function addUnitPriority(unit, priority) {
        priorities[unit] = priority;
    }

    function getPrioritizedUnits(unitsObj) {
        var units = [];
        for (var u in unitsObj) {
            units.push({unit: u, priority: priorities[u]});
        }
        units.sort(function (a, b) {
            return a.priority - b.priority;
        });
        return units;
    }

    function makeGetSet (unit, keepTime) {
        return function (value) {
            if (value != null) {
                get_set__set(this, unit, value);
                utils_hooks__hooks.updateOffset(this, keepTime);
                return this;
            } else {
                return get_set__get(this, unit);
            }
        };
    }

    function get_set__get (mom, unit) {
        return mom.isValid() ?
            mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]() : NaN;
    }

    function get_set__set (mom, unit, value) {
        if (mom.isValid()) {
            mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
        }
    }

    // MOMENTS

    function stringGet (units) {
        units = normalizeUnits(units);
        if (isFunction(this[units])) {
            return this[units]();
        }
        return this;
    }


    function stringSet (units, value) {
        if (typeof units === 'object') {
            units = normalizeObjectUnits(units);
            var prioritized = getPrioritizedUnits(units);
            for (var i = 0; i < prioritized.length; i++) {
                this[prioritized[i].unit](units[prioritized[i].unit]);
            }
        } else {
            units = normalizeUnits(units);
            if (isFunction(this[units])) {
                return this[units](value);
            }
        }
        return this;
    }

    function zeroFill(number, targetLength, forceSign) {
        var absNumber = '' + Math.abs(number),
            zerosToFill = targetLength - absNumber.length,
            sign = number >= 0;
        return (sign ? (forceSign ? '+' : '') : '-') +
            Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber;
    }

    var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g;

    var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g;

    var formatFunctions = {};

    var formatTokenFunctions = {};

    // token:    'M'
    // padded:   ['MM', 2]
    // ordinal:  'Mo'
    // callback: function () { this.month() + 1 }
    function addFormatToken (token, padded, ordinal, callback) {
        var func = callback;
        if (typeof callback === 'string') {
            func = function () {
                return this[callback]();
            };
        }
        if (token) {
            formatTokenFunctions[token] = func;
        }
        if (padded) {
            formatTokenFunctions[padded[0]] = function () {
                return zeroFill(func.apply(this, arguments), padded[1], padded[2]);
            };
        }
        if (ordinal) {
            formatTokenFunctions[ordinal] = function () {
                return this.localeData().ordinal(func.apply(this, arguments), token);
            };
        }
    }

    function removeFormattingTokens(input) {
        if (input.match(/\[[\s\S]/)) {
            return input.replace(/^\[|\]$/g, '');
        }
        return input.replace(/\\/g, '');
    }

    function makeFormatFunction(format) {
        var array = format.match(formattingTokens), i, length;

        for (i = 0, length = array.length; i < length; i++) {
            if (formatTokenFunctions[array[i]]) {
                array[i] = formatTokenFunctions[array[i]];
            } else {
                array[i] = removeFormattingTokens(array[i]);
            }
        }

        return function (mom) {
            var output = '', i;
            for (i = 0; i < length; i++) {
                output += array[i] instanceof Function ? array[i].call(mom, format) : array[i];
            }
            return output;
        };
    }

    // format date using native date object
    function formatMoment(m, format) {
        if (!m.isValid()) {
            return m.localeData().invalidDate();
        }

        format = expandFormat(format, m.localeData());
        formatFunctions[format] = formatFunctions[format] || makeFormatFunction(format);

        return formatFunctions[format](m);
    }

    function expandFormat(format, locale) {
        var i = 5;

        function replaceLongDateFormatTokens(input) {
            return locale.longDateFormat(input) || input;
        }

        localFormattingTokens.lastIndex = 0;
        while (i >= 0 && localFormattingTokens.test(format)) {
            format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
            localFormattingTokens.lastIndex = 0;
            i -= 1;
        }

        return format;
    }

    var match1         = /\d/;            //       0 - 9
    var match2         = /\d\d/;          //      00 - 99
    var match3         = /\d{3}/;         //     000 - 999
    var match4         = /\d{4}/;         //    0000 - 9999
    var match6         = /[+-]?\d{6}/;    // -999999 - 999999
    var match1to2      = /\d\d?/;         //       0 - 99
    var match3to4      = /\d\d\d\d?/;     //     999 - 9999
    var match5to6      = /\d\d\d\d\d\d?/; //   99999 - 999999
    var match1to3      = /\d{1,3}/;       //       0 - 999
    var match1to4      = /\d{1,4}/;       //       0 - 9999
    var match1to6      = /[+-]?\d{1,6}/;  // -999999 - 999999

    var matchUnsigned  = /\d+/;           //       0 - inf
    var matchSigned    = /[+-]?\d+/;      //    -inf - inf

    var matchOffset    = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z
    var matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi; // +00 -00 +00:00 -00:00 +0000 -0000 or Z

    var matchTimestamp = /[+-]?\d+(\.\d{1,3})?/; // 123456789 123456789.123

    // any word (or two) characters or numbers including two/three word month in arabic.
    // includes scottish gaelic two word and hyphenated months
    var matchWord = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i;


    var regexes = {};

    function addRegexToken (token, regex, strictRegex) {
        regexes[token] = isFunction(regex) ? regex : function (isStrict, localeData) {
            return (isStrict && strictRegex) ? strictRegex : regex;
        };
    }

    function getParseRegexForToken (token, config) {
        if (!hasOwnProp(regexes, token)) {
            return new RegExp(unescapeFormat(token));
        }

        return regexes[token](config._strict, config._locale);
    }

    // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
    function unescapeFormat(s) {
        return regexEscape(s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
            return p1 || p2 || p3 || p4;
        }));
    }

    function regexEscape(s) {
        return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
    }

    var tokens = {};

    function addParseToken (token, callback) {
        var i, func = callback;
        if (typeof token === 'string') {
            token = [token];
        }
        if (typeof callback === 'number') {
            func = function (input, array) {
                array[callback] = toInt(input);
            };
        }
        for (i = 0; i < token.length; i++) {
            tokens[token[i]] = func;
        }
    }

    function addWeekParseToken (token, callback) {
        addParseToken(token, function (input, array, config, token) {
            config._w = config._w || {};
            callback(input, config._w, config, token);
        });
    }

    function addTimeToArrayFromToken(token, input, config) {
        if (input != null && hasOwnProp(tokens, token)) {
            tokens[token](input, config._a, config, token);
        }
    }

    var YEAR = 0;
    var MONTH = 1;
    var DATE = 2;
    var HOUR = 3;
    var MINUTE = 4;
    var SECOND = 5;
    var MILLISECOND = 6;
    var WEEK = 7;
    var WEEKDAY = 8;

    var indexOf;

    if (Array.prototype.indexOf) {
        indexOf = Array.prototype.indexOf;
    } else {
        indexOf = function (o) {
            // I know
            var i;
            for (i = 0; i < this.length; ++i) {
                if (this[i] === o) {
                    return i;
                }
            }
            return -1;
        };
    }

    function daysInMonth(year, month) {
        return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
    }

    // FORMATTING

    addFormatToken('M', ['MM', 2], 'Mo', function () {
        return this.month() + 1;
    });

    addFormatToken('MMM', 0, 0, function (format) {
        return this.localeData().monthsShort(this, format);
    });

    addFormatToken('MMMM', 0, 0, function (format) {
        return this.localeData().months(this, format);
    });

    // ALIASES

    addUnitAlias('month', 'M');

    // PRIORITY

    addUnitPriority('month', 8);

    // PARSING

    addRegexToken('M',    match1to2);
    addRegexToken('MM',   match1to2, match2);
    addRegexToken('MMM',  function (isStrict, locale) {
        return locale.monthsShortRegex(isStrict);
    });
    addRegexToken('MMMM', function (isStrict, locale) {
        return locale.monthsRegex(isStrict);
    });

    addParseToken(['M', 'MM'], function (input, array) {
        array[MONTH] = toInt(input) - 1;
    });

    addParseToken(['MMM', 'MMMM'], function (input, array, config, token) {
        var month = config._locale.monthsParse(input, token, config._strict);
        // if we didn't find a month name, mark the date as invalid.
        if (month != null) {
            array[MONTH] = month;
        } else {
            getParsingFlags(config).invalidMonth = input;
        }
    });

    // LOCALES

    var MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/;
    var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_');
    function localeMonths (m, format) {
        if (!m) {
            return this._months;
        }
        return isArray(this._months) ? this._months[m.month()] :
            this._months[(this._months.isFormat || MONTHS_IN_FORMAT).test(format) ? 'format' : 'standalone'][m.month()];
    }

    var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_');
    function localeMonthsShort (m, format) {
        if (!m) {
            return this._monthsShort;
        }
        return isArray(this._monthsShort) ? this._monthsShort[m.month()] :
            this._monthsShort[MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'][m.month()];
    }

    function units_month__handleStrictParse(monthName, format, strict) {
        var i, ii, mom, llc = monthName.toLocaleLowerCase();
        if (!this._monthsParse) {
            // this is not used
            this._monthsParse = [];
            this._longMonthsParse = [];
            this._shortMonthsParse = [];
            for (i = 0; i < 12; ++i) {
                mom = create_utc__createUTC([2000, i]);
                this._shortMonthsParse[i] = this.monthsShort(mom, '').toLocaleLowerCase();
                this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase();
            }
        }

        if (strict) {
            if (format === 'MMM') {
                ii = indexOf.call(this._shortMonthsParse, llc);
                return ii !== -1 ? ii : null;
            } else {
                ii = indexOf.call(this._longMonthsParse, llc);
                return ii !== -1 ? ii : null;
            }
        } else {
            if (format === 'MMM') {
                ii = indexOf.call(this._shortMonthsParse, llc);
                if (ii !== -1) {
                    return ii;
                }
                ii = indexOf.call(this._longMonthsParse, llc);
                return ii !== -1 ? ii : null;
            } else {
                ii = indexOf.call(this._longMonthsParse, llc);
                if (ii !== -1) {
                    return ii;
                }
                ii = indexOf.call(this._shortMonthsParse, llc);
                return ii !== -1 ? ii : null;
            }
        }
    }

    function localeMonthsParse (monthName, format, strict) {
        var i, mom, regex;

        if (this._monthsParseExact) {
            return units_month__handleStrictParse.call(this, monthName, format, strict);
        }

        if (!this._monthsParse) {
            this._monthsParse = [];
            this._longMonthsParse = [];
            this._shortMonthsParse = [];
        }

        // TODO: add sorting
        // Sorting makes sure if one month (or abbr) is a prefix of another
        // see sorting in computeMonthsParse
        for (i = 0; i < 12; i++) {
            // make the regex if we don't have it already
            mom = create_utc__createUTC([2000, i]);
            if (strict && !this._longMonthsParse[i]) {
                this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i');
                this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i');
            }
            if (!strict && !this._monthsParse[i]) {
                regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
                this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
            }
            // test the regex
            if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) {
                return i;
            } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) {
                return i;
            } else if (!strict && this._monthsParse[i].test(monthName)) {
                return i;
            }
        }
    }

    // MOMENTS

    function setMonth (mom, value) {
        var dayOfMonth;

        if (!mom.isValid()) {
            // No op
            return mom;
        }

        if (typeof value === 'string') {
            if (/^\d+$/.test(value)) {
                value = toInt(value);
            } else {
                value = mom.localeData().monthsParse(value);
                // TODO: Another silent failure?
                if (typeof value !== 'number') {
                    return mom;
                }
            }
        }

        dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));
        mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
        return mom;
    }

    function getSetMonth (value) {
        if (value != null) {
            setMonth(this, value);
            utils_hooks__hooks.updateOffset(this, true);
            return this;
        } else {
            return get_set__get(this, 'Month');
        }
    }

    function getDaysInMonth () {
        return daysInMonth(this.year(), this.month());
    }

    var defaultMonthsShortRegex = matchWord;
    function monthsShortRegex (isStrict) {
        if (this._monthsParseExact) {
            if (!hasOwnProp(this, '_monthsRegex')) {
                computeMonthsParse.call(this);
            }
            if (isStrict) {
                return this._monthsShortStrictRegex;
            } else {
                return this._monthsShortRegex;
            }
        } else {
            if (!hasOwnProp(this, '_monthsShortRegex')) {
                this._monthsShortRegex = defaultMonthsShortRegex;
            }
            return this._monthsShortStrictRegex && isStrict ?
                this._monthsShortStrictRegex : this._monthsShortRegex;
        }
    }

    var defaultMonthsRegex = matchWord;
    function monthsRegex (isStrict) {
        if (this._monthsParseExact) {
            if (!hasOwnProp(this, '_monthsRegex')) {
                computeMonthsParse.call(this);
            }
            if (isStrict) {
                return this._monthsStrictRegex;
            } else {
                return this._monthsRegex;
            }
        } else {
            if (!hasOwnProp(this, '_monthsRegex')) {
                this._monthsRegex = defaultMonthsRegex;
            }
            return this._monthsStrictRegex && isStrict ?
                this._monthsStrictRegex : this._monthsRegex;
        }
    }

    function computeMonthsParse () {
        function cmpLenRev(a, b) {
            return b.length - a.length;
        }

        var shortPieces = [], longPieces = [], mixedPieces = [],
            i, mom;
        for (i = 0; i < 12; i++) {
            // make the regex if we don't have it already
            mom = create_utc__createUTC([2000, i]);
            shortPieces.push(this.monthsShort(mom, ''));
            longPieces.push(this.months(mom, ''));
            mixedPieces.push(this.months(mom, ''));
            mixedPieces.push(this.monthsShort(mom, ''));
        }
        // Sorting makes sure if one month (or abbr) is a prefix of another it
        // will match the longer piece.
        shortPieces.sort(cmpLenRev);
        longPieces.sort(cmpLenRev);
        mixedPieces.sort(cmpLenRev);
        for (i = 0; i < 12; i++) {
            shortPieces[i] = regexEscape(shortPieces[i]);
            longPieces[i] = regexEscape(longPieces[i]);
        }
        for (i = 0; i < 24; i++) {
            mixedPieces[i] = regexEscape(mixedPieces[i]);
        }

        this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
        this._monthsShortRegex = this._monthsRegex;
        this._monthsStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
        this._monthsShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
    }

    // FORMATTING

    addFormatToken('Y', 0, 0, function () {
        var y = this.year();
        return y <= 9999 ? '' + y : '+' + y;
    });

    addFormatToken(0, ['YY', 2], 0, function () {
        return this.year() % 100;
    });

    addFormatToken(0, ['YYYY',   4],       0, 'year');
    addFormatToken(0, ['YYYYY',  5],       0, 'year');
    addFormatToken(0, ['YYYYYY', 6, true], 0, 'year');

    // ALIASES

    addUnitAlias('year', 'y');

    // PRIORITIES

    addUnitPriority('year', 1);

    // PARSING

    addRegexToken('Y',      matchSigned);
    addRegexToken('YY',     match1to2, match2);
    addRegexToken('YYYY',   match1to4, match4);
    addRegexToken('YYYYY',  match1to6, match6);
    addRegexToken('YYYYYY', match1to6, match6);

    addParseToken(['YYYYY', 'YYYYYY'], YEAR);
    addParseToken('YYYY', function (input, array) {
        array[YEAR] = input.length === 2 ? utils_hooks__hooks.parseTwoDigitYear(input) : toInt(input);
    });
    addParseToken('YY', function (input, array) {
        array[YEAR] = utils_hooks__hooks.parseTwoDigitYear(input);
    });
    addParseToken('Y', function (input, array) {
        array[YEAR] = parseInt(input, 10);
    });

    // HELPERS

    function daysInYear(year) {
        return isLeapYear(year) ? 366 : 365;
    }

    function isLeapYear(year) {
        return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
    }

    // HOOKS

    utils_hooks__hooks.parseTwoDigitYear = function (input) {
        return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
    };

    // MOMENTS

    var getSetYear = makeGetSet('FullYear', true);

    function getIsLeapYear () {
        return isLeapYear(this.year());
    }

    function createDate (y, m, d, h, M, s, ms) {
        //can't just apply() to create a date:
        //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply
        var date = new Date(y, m, d, h, M, s, ms);

        //the date constructor remaps years 0-99 to 1900-1999
        if (y < 100 && y >= 0 && isFinite(date.getFullYear())) {
            date.setFullYear(y);
        }
        return date;
    }

    function createUTCDate (y) {
        var date = new Date(Date.UTC.apply(null, arguments));

        //the Date.UTC function remaps years 0-99 to 1900-1999
        if (y < 100 && y >= 0 && isFinite(date.getUTCFullYear())) {
            date.setUTCFullYear(y);
        }
        return date;
    }

    // start-of-first-week - start-of-year
    function firstWeekOffset(year, dow, doy) {
        var // first-week day -- which january is always in the first week (4 for iso, 1 for other)
            fwd = 7 + dow - doy,
            // first-week day local weekday -- which local weekday is fwd
            fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7;

        return -fwdlw + fwd - 1;
    }

    //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
    function dayOfYearFromWeeks(year, week, weekday, dow, doy) {
        var localWeekday = (7 + weekday - dow) % 7,
            weekOffset = firstWeekOffset(year, dow, doy),
            dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset,
            resYear, resDayOfYear;

        if (dayOfYear <= 0) {
            resYear = year - 1;
            resDayOfYear = daysInYear(resYear) + dayOfYear;
        } else if (dayOfYear > daysInYear(year)) {
            resYear = year + 1;
            resDayOfYear = dayOfYear - daysInYear(year);
        } else {
            resYear = year;
            resDayOfYear = dayOfYear;
        }

        return {
            year: resYear,
            dayOfYear: resDayOfYear
        };
    }

    function weekOfYear(mom, dow, doy) {
        var weekOffset = firstWeekOffset(mom.year(), dow, doy),
            week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1,
            resWeek, resYear;

        if (week < 1) {
            resYear = mom.year() - 1;
            resWeek = week + weeksInYear(resYear, dow, doy);
        } else if (week > weeksInYear(mom.year(), dow, doy)) {
            resWeek = week - weeksInYear(mom.year(), dow, doy);
            resYear = mom.year() + 1;
        } else {
            resYear = mom.year();
            resWeek = week;
        }

        return {
            week: resWeek,
            year: resYear
        };
    }

    function weeksInYear(year, dow, doy) {
        var weekOffset = firstWeekOffset(year, dow, doy),
            weekOffsetNext = firstWeekOffset(year + 1, dow, doy);
        return (daysInYear(year) - weekOffset + weekOffsetNext) / 7;
    }

    // FORMATTING

    addFormatToken('w', ['ww', 2], 'wo', 'week');
    addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek');

    // ALIASES

    addUnitAlias('week', 'w');
    addUnitAlias('isoWeek', 'W');

    // PRIORITIES

    addUnitPriority('week', 5);
    addUnitPriority('isoWeek', 5);

    // PARSING

    addRegexToken('w',  match1to2);
    addRegexToken('ww', match1to2, match2);
    addRegexToken('W',  match1to2);
    addRegexToken('WW', match1to2, match2);

    addWeekParseToken(['w', 'ww', 'W', 'WW'], function (input, week, config, token) {
        week[token.substr(0, 1)] = toInt(input);
    });

    // HELPERS

    // LOCALES

    function localeWeek (mom) {
        return weekOfYear(mom, this._week.dow, this._week.doy).week;
    }

    var defaultLocaleWeek = {
        dow : 0, // Sunday is the first day of the week.
        doy : 6  // The week that contains Jan 1st is the first week of the year.
    };

    function localeFirstDayOfWeek () {
        return this._week.dow;
    }

    function localeFirstDayOfYear () {
        return this._week.doy;
    }

    // MOMENTS

    function getSetWeek (input) {
        var week = this.localeData().week(this);
        return input == null ? week : this.add((input - week) * 7, 'd');
    }

    function getSetISOWeek (input) {
        var week = weekOfYear(this, 1, 4).week;
        return input == null ? week : this.add((input - week) * 7, 'd');
    }

    // FORMATTING

    addFormatToken('d', 0, 'do', 'day');

    addFormatToken('dd', 0, 0, function (format) {
        return this.localeData().weekdaysMin(this, format);
    });

    addFormatToken('ddd', 0, 0, function (format) {
        return this.localeData().weekdaysShort(this, format);
    });

    addFormatToken('dddd', 0, 0, function (format) {
        return this.localeData().weekdays(this, format);
    });

    addFormatToken('e', 0, 0, 'weekday');
    addFormatToken('E', 0, 0, 'isoWeekday');

    // ALIASES

    addUnitAlias('day', 'd');
    addUnitAlias('weekday', 'e');
    addUnitAlias('isoWeekday', 'E');

    // PRIORITY
    addUnitPriority('day', 11);
    addUnitPriority('weekday', 11);
    addUnitPriority('isoWeekday', 11);

    // PARSING

    addRegexToken('d',    match1to2);
    addRegexToken('e',    match1to2);
    addRegexToken('E',    match1to2);
    addRegexToken('dd',   function (isStrict, locale) {
        return locale.weekdaysMinRegex(isStrict);
    });
    addRegexToken('ddd',   function (isStrict, locale) {
        return locale.weekdaysShortRegex(isStrict);
    });
    addRegexToken('dddd',   function (isStrict, locale) {
        return locale.weekdaysRegex(isStrict);
    });

    addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) {
        var weekday = config._locale.weekdaysParse(input, token, config._strict);
        // if we didn't get a weekday name, mark the date as invalid
        if (weekday != null) {
            week.d = weekday;
        } else {
            getParsingFlags(config).invalidWeekday = input;
        }
    });

    addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) {
        week[token] = toInt(input);
    });

    // HELPERS

    function parseWeekday(input, locale) {
        if (typeof input !== 'string') {
            return input;
        }

        if (!isNaN(input)) {
            return parseInt(input, 10);
        }

        input = locale.weekdaysParse(input);
        if (typeof input === 'number') {
            return input;
        }

        return null;
    }

    function parseIsoWeekday(input, locale) {
        if (typeof input === 'string') {
            return locale.weekdaysParse(input) % 7 || 7;
        }
        return isNaN(input) ? null : input;
    }

    // LOCALES

    var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_');
    function localeWeekdays (m, format) {
        if (!m) {
            return this._weekdays;
        }
        return isArray(this._weekdays) ? this._weekdays[m.day()] :
            this._weekdays[this._weekdays.isFormat.test(format) ? 'format' : 'standalone'][m.day()];
    }

    var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_');
    function localeWeekdaysShort (m) {
        return (m) ? this._weekdaysShort[m.day()] : this._weekdaysShort;
    }

    var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_');
    function localeWeekdaysMin (m) {
        return (m) ? this._weekdaysMin[m.day()] : this._weekdaysMin;
    }

    function day_of_week__handleStrictParse(weekdayName, format, strict) {
        var i, ii, mom, llc = weekdayName.toLocaleLowerCase();
        if (!this._weekdaysParse) {
            this._weekdaysParse = [];
            this._shortWeekdaysParse = [];
            this._minWeekdaysParse = [];

            for (i = 0; i < 7; ++i) {
                mom = create_utc__createUTC([2000, 1]).day(i);
                this._minWeekdaysParse[i] = this.weekdaysMin(mom, '').toLocaleLowerCase();
                this._shortWeekdaysParse[i] = this.weekdaysShort(mom, '').toLocaleLowerCase();
                this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase();
            }
        }

        if (strict) {
            if (format === 'dddd') {
                ii = indexOf.call(this._weekdaysParse, llc);
                return ii !== -1 ? ii : null;
            } else if (format === 'ddd') {
                ii = indexOf.call(this._shortWeekdaysParse, llc);
                return ii !== -1 ? ii : null;
            } else {
                ii = indexOf.call(this._minWeekdaysParse, llc);
                return ii !== -1 ? ii : null;
            }
        } else {
            if (format === 'dddd') {
                ii = indexOf.call(this._weekdaysParse, llc);
                if (ii !== -1) {
                    return ii;
                }
                ii = indexOf.call(this._shortWeekdaysParse, llc);
                if (ii !== -1) {
                    return ii;
                }
                ii = indexOf.call(this._minWeekdaysParse, llc);
                return ii !== -1 ? ii : null;
            } else if (format === 'ddd') {
                ii = indexOf.call(this._shortWeekdaysParse, llc);
                if (ii !== -1) {
                    return ii;
                }
                ii = indexOf.call(this._weekdaysParse, llc);
                if (ii !== -1) {
                    return ii;
                }
                ii = indexOf.call(this._minWeekdaysParse, llc);
                return ii !== -1 ? ii : null;
            } else {
                ii = indexOf.call(this._minWeekdaysParse, llc);
                if (ii !== -1) {
                    return ii;
                }
                ii = indexOf.call(this._weekdaysParse, llc);
                if (ii !== -1) {
                    return ii;
                }
                ii = indexOf.call(this._shortWeekdaysParse, llc);
                return ii !== -1 ? ii : null;
            }
        }
    }

    function localeWeekdaysParse (weekdayName, format, strict) {
        var i, mom, regex;

        if (this._weekdaysParseExact) {
            return day_of_week__handleStrictParse.call(this, weekdayName, format, strict);
        }

        if (!this._weekdaysParse) {
            this._weekdaysParse = [];
            this._minWeekdaysParse = [];
            this._shortWeekdaysParse = [];
            this._fullWeekdaysParse = [];
        }

        for (i = 0; i < 7; i++) {
            // make the regex if we don't have it already

            mom = create_utc__createUTC([2000, 1]).day(i);
            if (strict && !this._fullWeekdaysParse[i]) {
                this._fullWeekdaysParse[i] = new RegExp('^' + this.weekdays(mom, '').replace('.', '\.?') + '$', 'i');
                this._shortWeekdaysParse[i] = new RegExp('^' + this.weekdaysShort(mom, '').replace('.', '\.?') + '$', 'i');
                this._minWeekdaysParse[i] = new RegExp('^' + this.weekdaysMin(mom, '').replace('.', '\.?') + '$', 'i');
            }
            if (!this._weekdaysParse[i]) {
                regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
                this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
            }
            // test the regex
            if (strict && format === 'dddd' && this._fullWeekdaysParse[i].test(weekdayName)) {
                return i;
            } else if (strict && format === 'ddd' && this._shortWeekdaysParse[i].test(weekdayName)) {
                return i;
            } else if (strict && format === 'dd' && this._minWeekdaysParse[i].test(weekdayName)) {
                return i;
            } else if (!strict && this._weekdaysParse[i].test(weekdayName)) {
                return i;
            }
        }
    }

    // MOMENTS

    function getSetDayOfWeek (input) {
        if (!this.isValid()) {
            return input != null ? this : NaN;
        }
        var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
        if (input != null) {
            input = parseWeekday(input, this.localeData());
            return this.add(input - day, 'd');
        } else {
            return day;
        }
    }

    function getSetLocaleDayOfWeek (input) {
        if (!this.isValid()) {
            return input != null ? this : NaN;
        }
        var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
        return input == null ? weekday : this.add(input - weekday, 'd');
    }

    function getSetISODayOfWeek (input) {
        if (!this.isValid()) {
            return input != null ? this : NaN;
        }

        // behaves the same as moment#day except
        // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
        // as a setter, sunday should belong to the previous week.

        if (input != null) {
            var weekday = parseIsoWeekday(input, this.localeData());
            return this.day(this.day() % 7 ? weekday : weekday - 7);
        } else {
            return this.day() || 7;
        }
    }

    var defaultWeekdaysRegex = matchWord;
    function weekdaysRegex (isStrict) {
        if (this._weekdaysParseExact) {
            if (!hasOwnProp(this, '_weekdaysRegex')) {
                computeWeekdaysParse.call(this);
            }
            if (isStrict) {
                return this._weekdaysStrictRegex;
            } else {
                return this._weekdaysRegex;
            }
        } else {
            if (!hasOwnProp(this, '_weekdaysRegex')) {
                this._weekdaysRegex = defaultWeekdaysRegex;
            }
            return this._weekdaysStrictRegex && isStrict ?
                this._weekdaysStrictRegex : this._weekdaysRegex;
        }
    }

    var defaultWeekdaysShortRegex = matchWord;
    function weekdaysShortRegex (isStrict) {
        if (this._weekdaysParseExact) {
            if (!hasOwnProp(this, '_weekdaysRegex')) {
                computeWeekdaysParse.call(this);
            }
            if (isStrict) {
                return this._weekdaysShortStrictRegex;
            } else {
                return this._weekdaysShortRegex;
            }
        } else {
            if (!hasOwnProp(this, '_weekdaysShortRegex')) {
                this._weekdaysShortRegex = defaultWeekdaysShortRegex;
            }
            return this._weekdaysShortStrictRegex && isStrict ?
                this._weekdaysShortStrictRegex : this._weekdaysShortRegex;
        }
    }

    var defaultWeekdaysMinRegex = matchWord;
    function weekdaysMinRegex (isStrict) {
        if (this._weekdaysParseExact) {
            if (!hasOwnProp(this, '_weekdaysRegex')) {
                computeWeekdaysParse.call(this);
            }
            if (isStrict) {
                return this._weekdaysMinStrictRegex;
            } else {
                return this._weekdaysMinRegex;
            }
        } else {
            if (!hasOwnProp(this, '_weekdaysMinRegex')) {
                this._weekdaysMinRegex = defaultWeekdaysMinRegex;
            }
            return this._weekdaysMinStrictRegex && isStrict ?
                this._weekdaysMinStrictRegex : this._weekdaysMinRegex;
        }
    }


    function computeWeekdaysParse () {
        function cmpLenRev(a, b) {
            return b.length - a.length;
        }

        var minPieces = [], shortPieces = [], longPieces = [], mixedPieces = [],
            i, mom, minp, shortp, longp;
        for (i = 0; i < 7; i++) {
            // make the regex if we don't have it already
            mom = create_utc__createUTC([2000, 1]).day(i);
            minp = this.weekdaysMin(mom, '');
            shortp = this.weekdaysShort(mom, '');
            longp = this.weekdays(mom, '');
            minPieces.push(minp);
            shortPieces.push(shortp);
            longPieces.push(longp);
            mixedPieces.push(minp);
            mixedPieces.push(shortp);
            mixedPieces.push(longp);
        }
        // Sorting makes sure if one weekday (or abbr) is a prefix of another it
        // will match the longer piece.
        minPieces.sort(cmpLenRev);
        shortPieces.sort(cmpLenRev);
        longPieces.sort(cmpLenRev);
        mixedPieces.sort(cmpLenRev);
        for (i = 0; i < 7; i++) {
            shortPieces[i] = regexEscape(shortPieces[i]);
            longPieces[i] = regexEscape(longPieces[i]);
            mixedPieces[i] = regexEscape(mixedPieces[i]);
        }

        this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
        this._weekdaysShortRegex = this._weekdaysRegex;
        this._weekdaysMinRegex = this._weekdaysRegex;

        this._weekdaysStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
        this._weekdaysShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
        this._weekdaysMinStrictRegex = new RegExp('^(' + minPieces.join('|') + ')', 'i');
    }

    // FORMATTING

    function hFormat() {
        return this.hours() % 12 || 12;
    }

    function kFormat() {
        return this.hours() || 24;
    }

    addFormatToken('H', ['HH', 2], 0, 'hour');
    addFormatToken('h', ['hh', 2], 0, hFormat);
    addFormatToken('k', ['kk', 2], 0, kFormat);

    addFormatToken('hmm', 0, 0, function () {
        return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2);
    });

    addFormatToken('hmmss', 0, 0, function () {
        return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2) +
            zeroFill(this.seconds(), 2);
    });

    addFormatToken('Hmm', 0, 0, function () {
        return '' + this.hours() + zeroFill(this.minutes(), 2);
    });

    addFormatToken('Hmmss', 0, 0, function () {
        return '' + this.hours() + zeroFill(this.minutes(), 2) +
            zeroFill(this.seconds(), 2);
    });

    function meridiem (token, lowercase) {
        addFormatToken(token, 0, 0, function () {
            return this.localeData().meridiem(this.hours(), this.minutes(), lowercase);
        });
    }

    meridiem('a', true);
    meridiem('A', false);

    // ALIASES

    addUnitAlias('hour', 'h');

    // PRIORITY
    addUnitPriority('hour', 13);

    // PARSING

    function matchMeridiem (isStrict, locale) {
        return locale._meridiemParse;
    }

    addRegexToken('a',  matchMeridiem);
    addRegexToken('A',  matchMeridiem);
    addRegexToken('H',  match1to2);
    addRegexToken('h',  match1to2);
    addRegexToken('HH', match1to2, match2);
    addRegexToken('hh', match1to2, match2);

    addRegexToken('hmm', match3to4);
    addRegexToken('hmmss', match5to6);
    addRegexToken('Hmm', match3to4);
    addRegexToken('Hmmss', match5to6);

    addParseToken(['H', 'HH'], HOUR);
    addParseToken(['a', 'A'], function (input, array, config) {
        config._isPm = config._locale.isPM(input);
        config._meridiem = input;
    });
    addParseToken(['h', 'hh'], function (input, array, config) {
        array[HOUR] = toInt(input);
        getParsingFlags(config).bigHour = true;
    });
    addParseToken('hmm', function (input, array, config) {
        var pos = input.length - 2;
        array[HOUR] = toInt(input.substr(0, pos));
        array[MINUTE] = toInt(input.substr(pos));
        getParsingFlags(config).bigHour = true;
    });
    addParseToken('hmmss', function (input, array, config) {
        var pos1 = input.length - 4;
        var pos2 = input.length - 2;
        array[HOUR] = toInt(input.substr(0, pos1));
        array[MINUTE] = toInt(input.substr(pos1, 2));
        array[SECOND] = toInt(input.substr(pos2));
        getParsingFlags(config).bigHour = true;
    });
    addParseToken('Hmm', function (input, array, config) {
        var pos = input.length - 2;
        array[HOUR] = toInt(input.substr(0, pos));
        array[MINUTE] = toInt(input.substr(pos));
    });
    addParseToken('Hmmss', function (input, array, config) {
        var pos1 = input.length - 4;
        var pos2 = input.length - 2;
        array[HOUR] = toInt(input.substr(0, pos1));
        array[MINUTE] = toInt(input.substr(pos1, 2));
        array[SECOND] = toInt(input.substr(pos2));
    });

    // LOCALES

    function localeIsPM (input) {
        // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
        // Using charAt should be more compatible.
        return ((input + '').toLowerCase().charAt(0) === 'p');
    }

    var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i;
    function localeMeridiem (hours, minutes, isLower) {
        if (hours > 11) {
            return isLower ? 'pm' : 'PM';
        } else {
            return isLower ? 'am' : 'AM';
        }
    }


    // MOMENTS

    // Setting the hour should keep the time, because the user explicitly
    // specified which hour he wants. So trying to maintain the same hour (in
    // a new timezone) makes sense. Adding/subtracting hours does not follow
    // this rule.
    var getSetHour = makeGetSet('Hours', true);

    var baseConfig = {
        calendar: defaultCalendar,
        longDateFormat: defaultLongDateFormat,
        invalidDate: defaultInvalidDate,
        ordinal: defaultOrdinal,
        ordinalParse: defaultOrdinalParse,
        relativeTime: defaultRelativeTime,

        months: defaultLocaleMonths,
        monthsShort: defaultLocaleMonthsShort,

        week: defaultLocaleWeek,

        weekdays: defaultLocaleWeekdays,
        weekdaysMin: defaultLocaleWeekdaysMin,
        weekdaysShort: defaultLocaleWeekdaysShort,

        meridiemParse: defaultLocaleMeridiemParse
    };

    // internal storage for locale config files
    var locales = {};
    var globalLocale;

    function normalizeLocale(key) {
        return key ? key.toLowerCase().replace('_', '-') : key;
    }

    // pick the locale from the array
    // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
    // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
    function chooseLocale(names) {
        var i = 0, j, next, locale, split;

        while (i < names.length) {
            split = normalizeLocale(names[i]).split('-');
            j = split.length;
            next = normalizeLocale(names[i + 1]);
            next = next ? next.split('-') : null;
            while (j > 0) {
                locale = loadLocale(split.slice(0, j).join('-'));
                if (locale) {
                    return locale;
                }
                if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
                    //the next array item is better than a shallower substring of this one
                    break;
                }
                j--;
            }
            i++;
        }
        return null;
    }

    function loadLocale(name) {
        var oldLocale = null;
        // TODO: Find a better way to register and load all the locales in Node
        if (!locales[name] && (typeof module !== 'undefined') &&
                module && module.exports) {
            try {
                oldLocale = globalLocale._abbr;
                require('./locale/' + name);
                // because defineLocale currently also sets the global locale, we
                // want to undo that for lazy loaded locales
                locale_locales__getSetGlobalLocale(oldLocale);
            } catch (e) { }
        }
        return locales[name];
    }

    // This function will load locale and then set the global locale.  If
    // no arguments are passed in, it will simply return the current global
    // locale key.
    function locale_locales__getSetGlobalLocale (key, values) {
        var data;
        if (key) {
            if (isUndefined(values)) {
                data = locale_locales__getLocale(key);
            }
            else {
                data = defineLocale(key, values);
            }

            if (data) {
                // moment.duration._locale = moment._locale = data;
                globalLocale = data;
            }
        }

        return globalLocale._abbr;
    }

    function defineLocale (name, config) {
        if (config !== null) {
            var parentConfig = baseConfig;
            config.abbr = name;
            if (locales[name] != null) {
                deprecateSimple('defineLocaleOverride',
                        'use moment.updateLocale(localeName, config) to change ' +
                        'an existing locale. moment.defineLocale(localeName, ' +
                        'config) should only be used for creating a new locale ' +
                        'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.');
                parentConfig = locales[name]._config;
            } else if (config.parentLocale != null) {
                if (locales[config.parentLocale] != null) {
                    parentConfig = locales[config.parentLocale]._config;
                } else {
                    // treat as if there is no base config
                    deprecateSimple('parentLocaleUndefined',
                            'specified parentLocale is not defined yet. See http://momentjs.com/guides/#/warnings/parent-locale/');
                }
            }
            locales[name] = new Locale(mergeConfigs(parentConfig, config));

            // backwards compat for now: also set the locale
            locale_locales__getSetGlobalLocale(name);

            return locales[name];
        } else {
            // useful for testing
            delete locales[name];
            return null;
        }
    }

    function updateLocale(name, config) {
        if (config != null) {
            var locale, parentConfig = baseConfig;
            // MERGE
            if (locales[name] != null) {
                parentConfig = locales[name]._config;
            }
            config = mergeConfigs(parentConfig, config);
            locale = new Locale(config);
            locale.parentLocale = locales[name];
            locales[name] = locale;

            // backwards compat for now: also set the locale
            locale_locales__getSetGlobalLocale(name);
        } else {
            // pass null for config to unupdate, useful for tests
            if (locales[name] != null) {
                if (locales[name].parentLocale != null) {
                    locales[name] = locales[name].parentLocale;
                } else if (locales[name] != null) {
                    delete locales[name];
                }
            }
        }
        return locales[name];
    }

    // returns locale data
    function locale_locales__getLocale (key) {
        var locale;

        if (key && key._locale && key._locale._abbr) {
            key = key._locale._abbr;
        }

        if (!key) {
            return globalLocale;
        }

        if (!isArray(key)) {
            //short-circuit everything else
            locale = loadLocale(key);
            if (locale) {
                return locale;
            }
            key = [key];
        }

        return chooseLocale(key);
    }

    function locale_locales__listLocales() {
        return keys(locales);
    }

    function checkOverflow (m) {
        var overflow;
        var a = m._a;

        if (a && getParsingFlags(m).overflow === -2) {
            overflow =
                a[MONTH]       < 0 || a[MONTH]       > 11  ? MONTH :
                a[DATE]        < 1 || a[DATE]        > daysInMonth(a[YEAR], a[MONTH]) ? DATE :
                a[HOUR]        < 0 || a[HOUR]        > 24 || (a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0)) ? HOUR :
                a[MINUTE]      < 0 || a[MINUTE]      > 59  ? MINUTE :
                a[SECOND]      < 0 || a[SECOND]      > 59  ? SECOND :
                a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND :
                -1;

            if (getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
                overflow = DATE;
            }
            if (getParsingFlags(m)._overflowWeeks && overflow === -1) {
                overflow = WEEK;
            }
            if (getParsingFlags(m)._overflowWeekday && overflow === -1) {
                overflow = WEEKDAY;
            }

            getParsingFlags(m).overflow = overflow;
        }

        return m;
    }

    // iso 8601 regex
    // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00)
    var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?/;
    var basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?/;

    var tzRegex = /Z|[+-]\d\d(?::?\d\d)?/;

    var isoDates = [
        ['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/],
        ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/],
        ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/],
        ['GGGG-[W]WW', /\d{4}-W\d\d/, false],
        ['YYYY-DDD', /\d{4}-\d{3}/],
        ['YYYY-MM', /\d{4}-\d\d/, false],
        ['YYYYYYMMDD', /[+-]\d{10}/],
        ['YYYYMMDD', /\d{8}/],
        // YYYYMM is NOT allowed by the standard
        ['GGGG[W]WWE', /\d{4}W\d{3}/],
        ['GGGG[W]WW', /\d{4}W\d{2}/, false],
        ['YYYYDDD', /\d{7}/]
    ];

    // iso time formats and regexes
    var isoTimes = [
        ['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/],
        ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/],
        ['HH:mm:ss', /\d\d:\d\d:\d\d/],
        ['HH:mm', /\d\d:\d\d/],
        ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/],
        ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/],
        ['HHmmss', /\d\d\d\d\d\d/],
        ['HHmm', /\d\d\d\d/],
        ['HH', /\d\d/]
    ];

    var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i;

    // date from iso format
    function configFromISO(config) {
        var i, l,
            string = config._i,
            match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string),
            allowTime, dateFormat, timeFormat, tzFormat;

        if (match) {
            getParsingFlags(config).iso = true;

            for (i = 0, l = isoDates.length; i < l; i++) {
                if (isoDates[i][1].exec(match[1])) {
                    dateFormat = isoDates[i][0];
                    allowTime = isoDates[i][2] !== false;
                    break;
                }
            }
            if (dateFormat == null) {
                config._isValid = false;
                return;
            }
            if (match[3]) {
                for (i = 0, l = isoTimes.length; i < l; i++) {
                    if (isoTimes[i][1].exec(match[3])) {
                        // match[2] should be 'T' or space
                        timeFormat = (match[2] || ' ') + isoTimes[i][0];
                        break;
                    }
                }
                if (timeFormat == null) {
                    config._isValid = false;
                    return;
                }
            }
            if (!allowTime && timeFormat != null) {
                config._isValid = false;
                return;
            }
            if (match[4]) {
                if (tzRegex.exec(match[4])) {
                    tzFormat = 'Z';
                } else {
                    config._isValid = false;
                    return;
                }
            }
            config._f = dateFormat + (timeFormat || '') + (tzFormat || '');
            configFromStringAndFormat(config);
        } else {
            config._isValid = false;
        }
    }

    // date from iso format or fallback
    function configFromString(config) {
        var matched = aspNetJsonRegex.exec(config._i);

        if (matched !== null) {
            config._d = new Date(+matched[1]);
            return;
        }

        configFromISO(config);
        if (config._isValid === false) {
            delete config._isValid;
            utils_hooks__hooks.createFromInputFallback(config);
        }
    }

    utils_hooks__hooks.createFromInputFallback = deprecate(
        'value provided is not in a recognized ISO format. moment construction falls back to js Date(), ' +
        'which is not reliable across all browsers and versions. Non ISO date formats are ' +
        'discouraged and will be removed in an upcoming major release. Please refer to ' +
        'http://momentjs.com/guides/#/warnings/js-date/ for more info.',
        function (config) {
            config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
        }
    );

    // Pick the first defined of two or three arguments.
    function defaults(a, b, c) {
        if (a != null) {
            return a;
        }
        if (b != null) {
            return b;
        }
        return c;
    }

    function currentDateArray(config) {
        // hooks is actually the exported moment object
        var nowValue = new Date(utils_hooks__hooks.now());
        if (config._useUTC) {
            return [nowValue.getUTCFullYear(), nowValue.getUTCMonth(), nowValue.getUTCDate()];
        }
        return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()];
    }

    // convert an array to a date.
    // the array should mirror the parameters below
    // note: all values past the year are optional and will default to the lowest possible value.
    // [year, month, day , hour, minute, second, millisecond]
    function configFromArray (config) {
        var i, date, input = [], currentDate, yearToUse;

        if (config._d) {
            return;
        }

        currentDate = currentDateArray(config);

        //compute day of the year from weeks and weekdays
        if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
            dayOfYearFromWeekInfo(config);
        }

        //if the day of the year is set, figure out what it is
        if (config._dayOfYear) {
            yearToUse = defaults(config._a[YEAR], currentDate[YEAR]);

            if (config._dayOfYear > daysInYear(yearToUse)) {
                getParsingFlags(config)._overflowDayOfYear = true;
            }

            date = createUTCDate(yearToUse, 0, config._dayOfYear);
            config._a[MONTH] = date.getUTCMonth();
            config._a[DATE] = date.getUTCDate();
        }

        // Default to current date.
        // * if no year, month, day of month are given, default to today
        // * if day of month is given, default month and year
        // * if month is given, default only year
        // * if year is given, don't default anything
        for (i = 0; i < 3 && config._a[i] == null; ++i) {
            config._a[i] = input[i] = currentDate[i];
        }

        // Zero out whatever was not defaulted, including time
        for (; i < 7; i++) {
            config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
        }

        // Check for 24:00:00.000
        if (config._a[HOUR] === 24 &&
                config._a[MINUTE] === 0 &&
                config._a[SECOND] === 0 &&
                config._a[MILLISECOND] === 0) {
            config._nextDay = true;
            config._a[HOUR] = 0;
        }

        config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input);
        // Apply timezone offset from input. The actual utcOffset can be changed
        // with parseZone.
        if (config._tzm != null) {
            config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
        }

        if (config._nextDay) {
            config._a[HOUR] = 24;
        }
    }

    function dayOfYearFromWeekInfo(config) {
        var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow;

        w = config._w;
        if (w.GG != null || w.W != null || w.E != null) {
            dow = 1;
            doy = 4;

            // TODO: We need to take the current isoWeekYear, but that depends on
            // how we interpret now (local, utc, fixed offset). So create
            // a now version of current config (take local/utc/offset flags, and
            // create now).
            weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(local__createLocal(), 1, 4).year);
            week = defaults(w.W, 1);
            weekday = defaults(w.E, 1);
            if (weekday < 1 || weekday > 7) {
                weekdayOverflow = true;
            }
        } else {
            dow = config._locale._week.dow;
            doy = config._locale._week.doy;

            weekYear = defaults(w.gg, config._a[YEAR], weekOfYear(local__createLocal(), dow, doy).year);
            week = defaults(w.w, 1);

            if (w.d != null) {
                // weekday -- low day numbers are considered next week
                weekday = w.d;
                if (weekday < 0 || weekday > 6) {
                    weekdayOverflow = true;
                }
            } else if (w.e != null) {
                // local weekday -- counting starts from begining of week
                weekday = w.e + dow;
                if (w.e < 0 || w.e > 6) {
                    weekdayOverflow = true;
                }
            } else {
                // default to begining of week
                weekday = dow;
            }
        }
        if (week < 1 || week > weeksInYear(weekYear, dow, doy)) {
            getParsingFlags(config)._overflowWeeks = true;
        } else if (weekdayOverflow != null) {
            getParsingFlags(config)._overflowWeekday = true;
        } else {
            temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy);
            config._a[YEAR] = temp.year;
            config._dayOfYear = temp.dayOfYear;
        }
    }

    // constant that refers to the ISO standard
    utils_hooks__hooks.ISO_8601 = function () {};

    // date from string and format string
    function configFromStringAndFormat(config) {
        // TODO: Move this to another part of the creation flow to prevent circular deps
        if (config._f === utils_hooks__hooks.ISO_8601) {
            configFromISO(config);
            return;
        }

        config._a = [];
        getParsingFlags(config).empty = true;

        // This array is used to make a Date, either with `new Date` or `Date.UTC`
        var string = '' + config._i,
            i, parsedInput, tokens, token, skipped,
            stringLength = string.length,
            totalParsedInputLength = 0;

        tokens = expandFormat(config._f, config._locale).match(formattingTokens) || [];

        for (i = 0; i < tokens.length; i++) {
            token = tokens[i];
            parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
            // console.log('token', token, 'parsedInput', parsedInput,
            //         'regex', getParseRegexForToken(token, config));
            if (parsedInput) {
                skipped = string.substr(0, string.indexOf(parsedInput));
                if (skipped.length > 0) {
                    getParsingFlags(config).unusedInput.push(skipped);
                }
                string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
                totalParsedInputLength += parsedInput.length;
            }
            // don't parse if it's not a known token
            if (formatTokenFunctions[token]) {
                if (parsedInput) {
                    getParsingFlags(config).empty = false;
                }
                else {
                    getParsingFlags(config).unusedTokens.push(token);
                }
                addTimeToArrayFromToken(token, parsedInput, config);
            }
            else if (config._strict && !parsedInput) {
                getParsingFlags(config).unusedTokens.push(token);
            }
        }

        // add remaining unparsed input length to the string
        getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength;
        if (string.length > 0) {
            getParsingFlags(config).unusedInput.push(string);
        }

        // clear _12h flag if hour is <= 12
        if (config._a[HOUR] <= 12 &&
            getParsingFlags(config).bigHour === true &&
            config._a[HOUR] > 0) {
            getParsingFlags(config).bigHour = undefined;
        }

        getParsingFlags(config).parsedDateParts = config._a.slice(0);
        getParsingFlags(config).meridiem = config._meridiem;
        // handle meridiem
        config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem);

        configFromArray(config);
        checkOverflow(config);
    }


    function meridiemFixWrap (locale, hour, meridiem) {
        var isPm;

        if (meridiem == null) {
            // nothing to do
            return hour;
        }
        if (locale.meridiemHour != null) {
            return locale.meridiemHour(hour, meridiem);
        } else if (locale.isPM != null) {
            // Fallback
            isPm = locale.isPM(meridiem);
            if (isPm && hour < 12) {
                hour += 12;
            }
            if (!isPm && hour === 12) {
                hour = 0;
            }
            return hour;
        } else {
            // this is not supposed to happen
            return hour;
        }
    }

    // date from string and array of format strings
    function configFromStringAndArray(config) {
        var tempConfig,
            bestMoment,

            scoreToBeat,
            i,
            currentScore;

        if (config._f.length === 0) {
            getParsingFlags(config).invalidFormat = true;
            config._d = new Date(NaN);
            return;
        }

        for (i = 0; i < config._f.length; i++) {
            currentScore = 0;
            tempConfig = copyConfig({}, config);
            if (config._useUTC != null) {
                tempConfig._useUTC = config._useUTC;
            }
            tempConfig._f = config._f[i];
            configFromStringAndFormat(tempConfig);

            if (!valid__isValid(tempConfig)) {
                continue;
            }

            // if there is any input that was not parsed add a penalty for that format
            currentScore += getParsingFlags(tempConfig).charsLeftOver;

            //or tokens
            currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10;

            getParsingFlags(tempConfig).score = currentScore;

            if (scoreToBeat == null || currentScore < scoreToBeat) {
                scoreToBeat = currentScore;
                bestMoment = tempConfig;
            }
        }

        extend(config, bestMoment || tempConfig);
    }

    function configFromObject(config) {
        if (config._d) {
            return;
        }

        var i = normalizeObjectUnits(config._i);
        config._a = map([i.year, i.month, i.day || i.date, i.hour, i.minute, i.second, i.millisecond], function (obj) {
            return obj && parseInt(obj, 10);
        });

        configFromArray(config);
    }

    function createFromConfig (config) {
        var res = new Moment(checkOverflow(prepareConfig(config)));
        if (res._nextDay) {
            // Adding is smart enough around DST
            res.add(1, 'd');
            res._nextDay = undefined;
        }

        return res;
    }

    function prepareConfig (config) {
        var input = config._i,
            format = config._f;

        config._locale = config._locale || locale_locales__getLocale(config._l);

        if (input === null || (format === undefined && input === '')) {
            return valid__createInvalid({nullInput: true});
        }

        if (typeof input === 'string') {
            config._i = input = config._locale.preparse(input);
        }

        if (isMoment(input)) {
            return new Moment(checkOverflow(input));
        } else if (isArray(format)) {
            configFromStringAndArray(config);
        } else if (isDate(input)) {
            config._d = input;
        } else if (format) {
            configFromStringAndFormat(config);
        }  else {
            configFromInput(config);
        }

        if (!valid__isValid(config)) {
            config._d = null;
        }

        return config;
    }

    function configFromInput(config) {
        var input = config._i;
        if (input === undefined) {
            config._d = new Date(utils_hooks__hooks.now());
        } else if (isDate(input)) {
            config._d = new Date(input.valueOf());
        } else if (typeof input === 'string') {
            configFromString(config);
        } else if (isArray(input)) {
            config._a = map(input.slice(0), function (obj) {
                return parseInt(obj, 10);
            });
            configFromArray(config);
        } else if (typeof(input) === 'object') {
            configFromObject(config);
        } else if (typeof(input) === 'number') {
            // from milliseconds
            config._d = new Date(input);
        } else {
            utils_hooks__hooks.createFromInputFallback(config);
        }
    }

    function createLocalOrUTC (input, format, locale, strict, isUTC) {
        var c = {};

        if (typeof(locale) === 'boolean') {
            strict = locale;
            locale = undefined;
        }

        if ((isObject(input) && isObjectEmpty(input)) ||
                (isArray(input) && input.length === 0)) {
            input = undefined;
        }
        // object construction must be done this way.
        // https://github.com/moment/moment/issues/1423
        c._isAMomentObject = true;
        c._useUTC = c._isUTC = isUTC;
        c._l = locale;
        c._i = input;
        c._f = format;
        c._strict = strict;

        return createFromConfig(c);
    }

    function local__createLocal (input, format, locale, strict) {
        return createLocalOrUTC(input, format, locale, strict, false);
    }

    var prototypeMin = deprecate(
        'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/',
        function () {
            var other = local__createLocal.apply(null, arguments);
            if (this.isValid() && other.isValid()) {
                return other < this ? this : other;
            } else {
                return valid__createInvalid();
            }
        }
    );

    var prototypeMax = deprecate(
        'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/',
        function () {
            var other = local__createLocal.apply(null, arguments);
            if (this.isValid() && other.isValid()) {
                return other > this ? this : other;
            } else {
                return valid__createInvalid();
            }
        }
    );

    // Pick a moment m from moments so that m[fn](other) is true for all
    // other. This relies on the function fn to be transitive.
    //
    // moments should either be an array of moment objects or an array, whose
    // first element is an array of moment objects.
    function pickBy(fn, moments) {
        var res, i;
        if (moments.length === 1 && isArray(moments[0])) {
            moments = moments[0];
        }
        if (!moments.length) {
            return local__createLocal();
        }
        res = moments[0];
        for (i = 1; i < moments.length; ++i) {
            if (!moments[i].isValid() || moments[i][fn](res)) {
                res = moments[i];
            }
        }
        return res;
    }

    // TODO: Use [].sort instead?
    function min () {
        var args = [].slice.call(arguments, 0);

        return pickBy('isBefore', args);
    }

    function max () {
        var args = [].slice.call(arguments, 0);

        return pickBy('isAfter', args);
    }

    var now = function () {
        return Date.now ? Date.now() : +(new Date());
    };

    function Duration (duration) {
        var normalizedInput = normalizeObjectUnits(duration),
            years = normalizedInput.year || 0,
            quarters = normalizedInput.quarter || 0,
            months = normalizedInput.month || 0,
            weeks = normalizedInput.week || 0,
            days = normalizedInput.day || 0,
            hours = normalizedInput.hour || 0,
            minutes = normalizedInput.minute || 0,
            seconds = normalizedInput.second || 0,
            milliseconds = normalizedInput.millisecond || 0;

        // representation for dateAddRemove
        this._milliseconds = +milliseconds +
            seconds * 1e3 + // 1000
            minutes * 6e4 + // 1000 * 60
            hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978
        // Because of dateAddRemove treats 24 hours as different from a
        // day when working around DST, we need to store them separately
        this._days = +days +
            weeks * 7;
        // It is impossible translate months into days without knowing
        // which months you are are talking about, so we have to store
        // it separately.
        this._months = +months +
            quarters * 3 +
            years * 12;

        this._data = {};

        this._locale = locale_locales__getLocale();

        this._bubble();
    }

    function isDuration (obj) {
        return obj instanceof Duration;
    }

    function absRound (number) {
        if (number < 0) {
            return Math.round(-1 * number) * -1;
        } else {
            return Math.round(number);
        }
    }

    // FORMATTING

    function offset (token, separator) {
        addFormatToken(token, 0, 0, function () {
            var offset = this.utcOffset();
            var sign = '+';
            if (offset < 0) {
                offset = -offset;
                sign = '-';
            }
            return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~(offset) % 60, 2);
        });
    }

    offset('Z', ':');
    offset('ZZ', '');

    // PARSING

    addRegexToken('Z',  matchShortOffset);
    addRegexToken('ZZ', matchShortOffset);
    addParseToken(['Z', 'ZZ'], function (input, array, config) {
        config._useUTC = true;
        config._tzm = offsetFromString(matchShortOffset, input);
    });

    // HELPERS

    // timezone chunker
    // '+10:00' > ['10',  '00']
    // '-1530'  > ['-15', '30']
    var chunkOffset = /([\+\-]|\d\d)/gi;

    function offsetFromString(matcher, string) {
        var matches = ((string || '').match(matcher) || []);
        var chunk   = matches[matches.length - 1] || [];
        var parts   = (chunk + '').match(chunkOffset) || ['-', 0, 0];
        var minutes = +(parts[1] * 60) + toInt(parts[2]);

        return parts[0] === '+' ? minutes : -minutes;
    }

    // Return a moment from input, that is local/utc/zone equivalent to model.
    function cloneWithOffset(input, model) {
        var res, diff;
        if (model._isUTC) {
            res = model.clone();
            diff = (isMoment(input) || isDate(input) ? input.valueOf() : local__createLocal(input).valueOf()) - res.valueOf();
            // Use low-level api, because this fn is low-level api.
            res._d.setTime(res._d.valueOf() + diff);
            utils_hooks__hooks.updateOffset(res, false);
            return res;
        } else {
            return local__createLocal(input).local();
        }
    }

    function getDateOffset (m) {
        // On Firefox.24 Date#getTimezoneOffset returns a floating point.
        // https://github.com/moment/moment/pull/1871
        return -Math.round(m._d.getTimezoneOffset() / 15) * 15;
    }

    // HOOKS

    // This function will be called whenever a moment is mutated.
    // It is intended to keep the offset in sync with the timezone.
    utils_hooks__hooks.updateOffset = function () {};

    // MOMENTS

    // keepLocalTime = true means only change the timezone, without
    // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
    // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
    // +0200, so we adjust the time as needed, to be valid.
    //
    // Keeping the time actually adds/subtracts (one hour)
    // from the actual represented time. That is why we call updateOffset
    // a second time. In case it wants us to change the offset again
    // _changeInProgress == true case, then we have to adjust, because
    // there is no such time in the given timezone.
    function getSetOffset (input, keepLocalTime) {
        var offset = this._offset || 0,
            localAdjust;
        if (!this.isValid()) {
            return input != null ? this : NaN;
        }
        if (input != null) {
            if (typeof input === 'string') {
                input = offsetFromString(matchShortOffset, input);
            } else if (Math.abs(input) < 16) {
                input = input * 60;
            }
            if (!this._isUTC && keepLocalTime) {
                localAdjust = getDateOffset(this);
            }
            this._offset = input;
            this._isUTC = true;
            if (localAdjust != null) {
                this.add(localAdjust, 'm');
            }
            if (offset !== input) {
                if (!keepLocalTime || this._changeInProgress) {
                    add_subtract__addSubtract(this, create__createDuration(input - offset, 'm'), 1, false);
                } else if (!this._changeInProgress) {
                    this._changeInProgress = true;
                    utils_hooks__hooks.updateOffset(this, true);
                    this._changeInProgress = null;
                }
            }
            return this;
        } else {
            return this._isUTC ? offset : getDateOffset(this);
        }
    }

    function getSetZone (input, keepLocalTime) {
        if (input != null) {
            if (typeof input !== 'string') {
                input = -input;
            }

            this.utcOffset(input, keepLocalTime);

            return this;
        } else {
            return -this.utcOffset();
        }
    }

    function setOffsetToUTC (keepLocalTime) {
        return this.utcOffset(0, keepLocalTime);
    }

    function setOffsetToLocal (keepLocalTime) {
        if (this._isUTC) {
            this.utcOffset(0, keepLocalTime);
            this._isUTC = false;

            if (keepLocalTime) {
                this.subtract(getDateOffset(this), 'm');
            }
        }
        return this;
    }

    function setOffsetToParsedOffset () {
        if (this._tzm) {
            this.utcOffset(this._tzm);
        } else if (typeof this._i === 'string') {
            var tZone = offsetFromString(matchOffset, this._i);

            if (tZone === 0) {
                this.utcOffset(0, true);
            } else {
                this.utcOffset(offsetFromString(matchOffset, this._i));
            }
        }
        return this;
    }

    function hasAlignedHourOffset (input) {
        if (!this.isValid()) {
            return false;
        }
        input = input ? local__createLocal(input).utcOffset() : 0;

        return (this.utcOffset() - input) % 60 === 0;
    }

    function isDaylightSavingTime () {
        return (
            this.utcOffset() > this.clone().month(0).utcOffset() ||
            this.utcOffset() > this.clone().month(5).utcOffset()
        );
    }

    function isDaylightSavingTimeShifted () {
        if (!isUndefined(this._isDSTShifted)) {
            return this._isDSTShifted;
        }

        var c = {};

        copyConfig(c, this);
        c = prepareConfig(c);

        if (c._a) {
            var other = c._isUTC ? create_utc__createUTC(c._a) : local__createLocal(c._a);
            this._isDSTShifted = this.isValid() &&
                compareArrays(c._a, other.toArray()) > 0;
        } else {
            this._isDSTShifted = false;
        }

        return this._isDSTShifted;
    }

    function isLocal () {
        return this.isValid() ? !this._isUTC : false;
    }

    function isUtcOffset () {
        return this.isValid() ? this._isUTC : false;
    }

    function isUtc () {
        return this.isValid() ? this._isUTC && this._offset === 0 : false;
    }

    // ASP.NET json date format regex
    var aspNetRegex = /^(\-)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/;

    // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
    // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
    // and further modified to allow for strings containing both week and day
    var isoRegex = /^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/;

    function create__createDuration (input, key) {
        var duration = input,
            // matching against regexp is expensive, do it on demand
            match = null,
            sign,
            ret,
            diffRes;

        if (isDuration(input)) {
            duration = {
                ms : input._milliseconds,
                d  : input._days,
                M  : input._months
            };
        } else if (typeof input === 'number') {
            duration = {};
            if (key) {
                duration[key] = input;
            } else {
                duration.milliseconds = input;
            }
        } else if (!!(match = aspNetRegex.exec(input))) {
            sign = (match[1] === '-') ? -1 : 1;
            duration = {
                y  : 0,
                d  : toInt(match[DATE])                         * sign,
                h  : toInt(match[HOUR])                         * sign,
                m  : toInt(match[MINUTE])                       * sign,
                s  : toInt(match[SECOND])                       * sign,
                ms : toInt(absRound(match[MILLISECOND] * 1000)) * sign // the millisecond decimal point is included in the match
            };
        } else if (!!(match = isoRegex.exec(input))) {
            sign = (match[1] === '-') ? -1 : 1;
            duration = {
                y : parseIso(match[2], sign),
                M : parseIso(match[3], sign),
                w : parseIso(match[4], sign),
                d : parseIso(match[5], sign),
                h : parseIso(match[6], sign),
                m : parseIso(match[7], sign),
                s : parseIso(match[8], sign)
            };
        } else if (duration == null) {// checks for null or undefined
            duration = {};
        } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) {
            diffRes = momentsDifference(local__createLocal(duration.from), local__createLocal(duration.to));

            duration = {};
            duration.ms = diffRes.milliseconds;
            duration.M = diffRes.months;
        }

        ret = new Duration(duration);

        if (isDuration(input) && hasOwnProp(input, '_locale')) {
            ret._locale = input._locale;
        }

        return ret;
    }

    create__createDuration.fn = Duration.prototype;

    function parseIso (inp, sign) {
        // We'd normally use ~~inp for this, but unfortunately it also
        // converts floats to ints.
        // inp may be undefined, so careful calling replace on it.
        var res = inp && parseFloat(inp.replace(',', '.'));
        // apply sign while we're at it
        return (isNaN(res) ? 0 : res) * sign;
    }

    function positiveMomentsDifference(base, other) {
        var res = {milliseconds: 0, months: 0};

        res.months = other.month() - base.month() +
            (other.year() - base.year()) * 12;
        if (base.clone().add(res.months, 'M').isAfter(other)) {
            --res.months;
        }

        res.milliseconds = +other - +(base.clone().add(res.months, 'M'));

        return res;
    }

    function momentsDifference(base, other) {
        var res;
        if (!(base.isValid() && other.isValid())) {
            return {milliseconds: 0, months: 0};
        }

        other = cloneWithOffset(other, base);
        if (base.isBefore(other)) {
            res = positiveMomentsDifference(base, other);
        } else {
            res = positiveMomentsDifference(other, base);
            res.milliseconds = -res.milliseconds;
            res.months = -res.months;
        }

        return res;
    }

    // TODO: remove 'name' arg after deprecation is removed
    function createAdder(direction, name) {
        return function (val, period) {
            var dur, tmp;
            //invert the arguments, but complain about it
            if (period !== null && !isNaN(+period)) {
                deprecateSimple(name, 'moment().' + name  + '(period, number) is deprecated. Please use moment().' + name + '(number, period). ' +
                'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.');
                tmp = val; val = period; period = tmp;
            }

            val = typeof val === 'string' ? +val : val;
            dur = create__createDuration(val, period);
            add_subtract__addSubtract(this, dur, direction);
            return this;
        };
    }

    function add_subtract__addSubtract (mom, duration, isAdding, updateOffset) {
        var milliseconds = duration._milliseconds,
            days = absRound(duration._days),
            months = absRound(duration._months);

        if (!mom.isValid()) {
            // No op
            return;
        }

        updateOffset = updateOffset == null ? true : updateOffset;

        if (milliseconds) {
            mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding);
        }
        if (days) {
            get_set__set(mom, 'Date', get_set__get(mom, 'Date') + days * isAdding);
        }
        if (months) {
            setMonth(mom, get_set__get(mom, 'Month') + months * isAdding);
        }
        if (updateOffset) {
            utils_hooks__hooks.updateOffset(mom, days || months);
        }
    }

    var add_subtract__add      = createAdder(1, 'add');
    var add_subtract__subtract = createAdder(-1, 'subtract');

    function getCalendarFormat(myMoment, now) {
        var diff = myMoment.diff(now, 'days', true);
        return diff < -6 ? 'sameElse' :
                diff < -1 ? 'lastWeek' :
                diff < 0 ? 'lastDay' :
                diff < 1 ? 'sameDay' :
                diff < 2 ? 'nextDay' :
                diff < 7 ? 'nextWeek' : 'sameElse';
    }

    function moment_calendar__calendar (time, formats) {
        // We want to compare the start of today, vs this.
        // Getting start-of-today depends on whether we're local/utc/offset or not.
        var now = time || local__createLocal(),
            sod = cloneWithOffset(now, this).startOf('day'),
            format = utils_hooks__hooks.calendarFormat(this, sod) || 'sameElse';

        var output = formats && (isFunction(formats[format]) ? formats[format].call(this, now) : formats[format]);

        return this.format(output || this.localeData().calendar(format, this, local__createLocal(now)));
    }

    function clone () {
        return new Moment(this);
    }

    function isAfter (input, units) {
        var localInput = isMoment(input) ? input : local__createLocal(input);
        if (!(this.isValid() && localInput.isValid())) {
            return false;
        }
        units = normalizeUnits(!isUndefined(units) ? units : 'millisecond');
        if (units === 'millisecond') {
            return this.valueOf() > localInput.valueOf();
        } else {
            return localInput.valueOf() < this.clone().startOf(units).valueOf();
        }
    }

    function isBefore (input, units) {
        var localInput = isMoment(input) ? input : local__createLocal(input);
        if (!(this.isValid() && localInput.isValid())) {
            return false;
        }
        units = normalizeUnits(!isUndefined(units) ? units : 'millisecond');
        if (units === 'millisecond') {
            return this.valueOf() < localInput.valueOf();
        } else {
            return this.clone().endOf(units).valueOf() < localInput.valueOf();
        }
    }

    function isBetween (from, to, units, inclusivity) {
        inclusivity = inclusivity || '()';
        return (inclusivity[0] === '(' ? this.isAfter(from, units) : !this.isBefore(from, units)) &&
            (inclusivity[1] === ')' ? this.isBefore(to, units) : !this.isAfter(to, units));
    }

    function isSame (input, units) {
        var localInput = isMoment(input) ? input : local__createLocal(input),
            inputMs;
        if (!(this.isValid() && localInput.isValid())) {
            return false;
        }
        units = normalizeUnits(units || 'millisecond');
        if (units === 'millisecond') {
            return this.valueOf() === localInput.valueOf();
        } else {
            inputMs = localInput.valueOf();
            return this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf();
        }
    }

    function isSameOrAfter (input, units) {
        return this.isSame(input, units) || this.isAfter(input,units);
    }

    function isSameOrBefore (input, units) {
        return this.isSame(input, units) || this.isBefore(input,units);
    }

    function diff (input, units, asFloat) {
        var that,
            zoneDelta,
            delta, output;

        if (!this.isValid()) {
            return NaN;
        }

        that = cloneWithOffset(input, this);

        if (!that.isValid()) {
            return NaN;
        }

        zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4;

        units = normalizeUnits(units);

        if (units === 'year' || units === 'month' || units === 'quarter') {
            output = monthDiff(this, that);
            if (units === 'quarter') {
                output = output / 3;
            } else if (units === 'year') {
                output = output / 12;
            }
        } else {
            delta = this - that;
            output = units === 'second' ? delta / 1e3 : // 1000
                units === 'minute' ? delta / 6e4 : // 1000 * 60
                units === 'hour' ? delta / 36e5 : // 1000 * 60 * 60
                units === 'day' ? (delta - zoneDelta) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
                units === 'week' ? (delta - zoneDelta) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
                delta;
        }
        return asFloat ? output : absFloor(output);
    }

    function monthDiff (a, b) {
        // difference in months
        var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()),
            // b is in (anchor - 1 month, anchor + 1 month)
            anchor = a.clone().add(wholeMonthDiff, 'months'),
            anchor2, adjust;

        if (b - anchor < 0) {
            anchor2 = a.clone().add(wholeMonthDiff - 1, 'months');
            // linear across the month
            adjust = (b - anchor) / (anchor - anchor2);
        } else {
            anchor2 = a.clone().add(wholeMonthDiff + 1, 'months');
            // linear across the month
            adjust = (b - anchor) / (anchor2 - anchor);
        }

        //check for negative zero, return zero if negative zero
        return -(wholeMonthDiff + adjust) || 0;
    }

    utils_hooks__hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ';
    utils_hooks__hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]';

    function toString () {
        return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
    }

    function moment_format__toISOString () {
        var m = this.clone().utc();
        if (0 < m.year() && m.year() <= 9999) {
            if (isFunction(Date.prototype.toISOString)) {
                // native implementation is ~50x faster, use it when we can
                return this.toDate().toISOString();
            } else {
                return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
            }
        } else {
            return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
        }
    }

    function format (inputString) {
        if (!inputString) {
            inputString = this.isUtc() ? utils_hooks__hooks.defaultFormatUtc : utils_hooks__hooks.defaultFormat;
        }
        var output = formatMoment(this, inputString);
        return this.localeData().postformat(output);
    }

    function from (time, withoutSuffix) {
        if (this.isValid() &&
                ((isMoment(time) && time.isValid()) ||
                 local__createLocal(time).isValid())) {
            return create__createDuration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix);
        } else {
            return this.localeData().invalidDate();
        }
    }

    function fromNow (withoutSuffix) {
        return this.from(local__createLocal(), withoutSuffix);
    }

    function to (time, withoutSuffix) {
        if (this.isValid() &&
                ((isMoment(time) && time.isValid()) ||
                 local__createLocal(time).isValid())) {
            return create__createDuration({from: this, to: time}).locale(this.locale()).humanize(!withoutSuffix);
        } else {
            return this.localeData().invalidDate();
        }
    }

    function toNow (withoutSuffix) {
        return this.to(local__createLocal(), withoutSuffix);
    }

    // If passed a locale key, it will set the locale for this
    // instance.  Otherwise, it will return the locale configuration
    // variables for this instance.
    function locale (key) {
        var newLocaleData;

        if (key === undefined) {
            return this._locale._abbr;
        } else {
            newLocaleData = locale_locales__getLocale(key);
            if (newLocaleData != null) {
                this._locale = newLocaleData;
            }
            return this;
        }
    }

    var lang = deprecate(
        'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.',
        function (key) {
            if (key === undefined) {
                return this.localeData();
            } else {
                return this.locale(key);
            }
        }
    );

    function localeData () {
        return this._locale;
    }

    function startOf (units) {
        units = normalizeUnits(units);
        // the following switch intentionally omits break keywords
        // to utilize falling through the cases.
        switch (units) {
            case 'year':
                this.month(0);
                /* falls through */
            case 'quarter':
            case 'month':
                this.date(1);
                /* falls through */
            case 'week':
            case 'isoWeek':
            case 'day':
            case 'date':
                this.hours(0);
                /* falls through */
            case 'hour':
                this.minutes(0);
                /* falls through */
            case 'minute':
                this.seconds(0);
                /* falls through */
            case 'second':
                this.milliseconds(0);
        }

        // weeks are a special case
        if (units === 'week') {
            this.weekday(0);
        }
        if (units === 'isoWeek') {
            this.isoWeekday(1);
        }

        // quarters are also special
        if (units === 'quarter') {
            this.month(Math.floor(this.month() / 3) * 3);
        }

        return this;
    }

    function endOf (units) {
        units = normalizeUnits(units);
        if (units === undefined || units === 'millisecond') {
            return this;
        }

        // 'date' is an alias for 'day', so it should be considered as such.
        if (units === 'date') {
            units = 'day';
        }

        return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms');
    }

    function to_type__valueOf () {
        return this._d.valueOf() - ((this._offset || 0) * 60000);
    }

    function unix () {
        return Math.floor(this.valueOf() / 1000);
    }

    function toDate () {
        return new Date(this.valueOf());
    }

    function toArray () {
        var m = this;
        return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()];
    }

    function toObject () {
        var m = this;
        return {
            years: m.year(),
            months: m.month(),
            date: m.date(),
            hours: m.hours(),
            minutes: m.minutes(),
            seconds: m.seconds(),
            milliseconds: m.milliseconds()
        };
    }

    function toJSON () {
        // new Date(NaN).toJSON() === null
        return this.isValid() ? this.toISOString() : null;
    }

    function moment_valid__isValid () {
        return valid__isValid(this);
    }

    function parsingFlags () {
        return extend({}, getParsingFlags(this));
    }

    function invalidAt () {
        return getParsingFlags(this).overflow;
    }

    function creationData() {
        return {
            input: this._i,
            format: this._f,
            locale: this._locale,
            isUTC: this._isUTC,
            strict: this._strict
        };
    }

    // FORMATTING

    addFormatToken(0, ['gg', 2], 0, function () {
        return this.weekYear() % 100;
    });

    addFormatToken(0, ['GG', 2], 0, function () {
        return this.isoWeekYear() % 100;
    });

    function addWeekYearFormatToken (token, getter) {
        addFormatToken(0, [token, token.length], 0, getter);
    }

    addWeekYearFormatToken('gggg',     'weekYear');
    addWeekYearFormatToken('ggggg',    'weekYear');
    addWeekYearFormatToken('GGGG',  'isoWeekYear');
    addWeekYearFormatToken('GGGGG', 'isoWeekYear');

    // ALIASES

    addUnitAlias('weekYear', 'gg');
    addUnitAlias('isoWeekYear', 'GG');

    // PRIORITY

    addUnitPriority('weekYear', 1);
    addUnitPriority('isoWeekYear', 1);


    // PARSING

    addRegexToken('G',      matchSigned);
    addRegexToken('g',      matchSigned);
    addRegexToken('GG',     match1to2, match2);
    addRegexToken('gg',     match1to2, match2);
    addRegexToken('GGGG',   match1to4, match4);
    addRegexToken('gggg',   match1to4, match4);
    addRegexToken('GGGGG',  match1to6, match6);
    addRegexToken('ggggg',  match1to6, match6);

    addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (input, week, config, token) {
        week[token.substr(0, 2)] = toInt(input);
    });

    addWeekParseToken(['gg', 'GG'], function (input, week, config, token) {
        week[token] = utils_hooks__hooks.parseTwoDigitYear(input);
    });

    // MOMENTS

    function getSetWeekYear (input) {
        return getSetWeekYearHelper.call(this,
                input,
                this.week(),
                this.weekday(),
                this.localeData()._week.dow,
                this.localeData()._week.doy);
    }

    function getSetISOWeekYear (input) {
        return getSetWeekYearHelper.call(this,
                input, this.isoWeek(), this.isoWeekday(), 1, 4);
    }

    function getISOWeeksInYear () {
        return weeksInYear(this.year(), 1, 4);
    }

    function getWeeksInYear () {
        var weekInfo = this.localeData()._week;
        return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
    }

    function getSetWeekYearHelper(input, week, weekday, dow, doy) {
        var weeksTarget;
        if (input == null) {
            return weekOfYear(this, dow, doy).year;
        } else {
            weeksTarget = weeksInYear(input, dow, doy);
            if (week > weeksTarget) {
                week = weeksTarget;
            }
            return setWeekAll.call(this, input, week, weekday, dow, doy);
        }
    }

    function setWeekAll(weekYear, week, weekday, dow, doy) {
        var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy),
            date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear);

        this.year(date.getUTCFullYear());
        this.month(date.getUTCMonth());
        this.date(date.getUTCDate());
        return this;
    }

    // FORMATTING

    addFormatToken('Q', 0, 'Qo', 'quarter');

    // ALIASES

    addUnitAlias('quarter', 'Q');

    // PRIORITY

    addUnitPriority('quarter', 7);

    // PARSING

    addRegexToken('Q', match1);
    addParseToken('Q', function (input, array) {
        array[MONTH] = (toInt(input) - 1) * 3;
    });

    // MOMENTS

    function getSetQuarter (input) {
        return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
    }

    // FORMATTING

    addFormatToken('D', ['DD', 2], 'Do', 'date');

    // ALIASES

    addUnitAlias('date', 'D');

    // PRIOROITY
    addUnitPriority('date', 9);

    // PARSING

    addRegexToken('D',  match1to2);
    addRegexToken('DD', match1to2, match2);
    addRegexToken('Do', function (isStrict, locale) {
        return isStrict ? locale._ordinalParse : locale._ordinalParseLenient;
    });

    addParseToken(['D', 'DD'], DATE);
    addParseToken('Do', function (input, array) {
        array[DATE] = toInt(input.match(match1to2)[0], 10);
    });

    // MOMENTS

    var getSetDayOfMonth = makeGetSet('Date', true);

    // FORMATTING

    addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear');

    // ALIASES

    addUnitAlias('dayOfYear', 'DDD');

    // PRIORITY
    addUnitPriority('dayOfYear', 4);

    // PARSING

    addRegexToken('DDD',  match1to3);
    addRegexToken('DDDD', match3);
    addParseToken(['DDD', 'DDDD'], function (input, array, config) {
        config._dayOfYear = toInt(input);
    });

    // HELPERS

    // MOMENTS

    function getSetDayOfYear (input) {
        var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1;
        return input == null ? dayOfYear : this.add((input - dayOfYear), 'd');
    }

    // FORMATTING

    addFormatToken('m', ['mm', 2], 0, 'minute');

    // ALIASES

    addUnitAlias('minute', 'm');

    // PRIORITY

    addUnitPriority('minute', 14);

    // PARSING

    addRegexToken('m',  match1to2);
    addRegexToken('mm', match1to2, match2);
    addParseToken(['m', 'mm'], MINUTE);

    // MOMENTS

    var getSetMinute = makeGetSet('Minutes', false);

    // FORMATTING

    addFormatToken('s', ['ss', 2], 0, 'second');

    // ALIASES

    addUnitAlias('second', 's');

    // PRIORITY

    addUnitPriority('second', 15);

    // PARSING

    addRegexToken('s',  match1to2);
    addRegexToken('ss', match1to2, match2);
    addParseToken(['s', 'ss'], SECOND);

    // MOMENTS

    var getSetSecond = makeGetSet('Seconds', false);

    // FORMATTING

    addFormatToken('S', 0, 0, function () {
        return ~~(this.millisecond() / 100);
    });

    addFormatToken(0, ['SS', 2], 0, function () {
        return ~~(this.millisecond() / 10);
    });

    addFormatToken(0, ['SSS', 3], 0, 'millisecond');
    addFormatToken(0, ['SSSS', 4], 0, function () {
        return this.millisecond() * 10;
    });
    addFormatToken(0, ['SSSSS', 5], 0, function () {
        return this.millisecond() * 100;
    });
    addFormatToken(0, ['SSSSSS', 6], 0, function () {
        return this.millisecond() * 1000;
    });
    addFormatToken(0, ['SSSSSSS', 7], 0, function () {
        return this.millisecond() * 10000;
    });
    addFormatToken(0, ['SSSSSSSS', 8], 0, function () {
        return this.millisecond() * 100000;
    });
    addFormatToken(0, ['SSSSSSSSS', 9], 0, function () {
        return this.millisecond() * 1000000;
    });


    // ALIASES

    addUnitAlias('millisecond', 'ms');

    // PRIORITY

    addUnitPriority('millisecond', 16);

    // PARSING

    addRegexToken('S',    match1to3, match1);
    addRegexToken('SS',   match1to3, match2);
    addRegexToken('SSS',  match1to3, match3);

    var token;
    for (token = 'SSSS'; token.length <= 9; token += 'S') {
        addRegexToken(token, matchUnsigned);
    }

    function parseMs(input, array) {
        array[MILLISECOND] = toInt(('0.' + input) * 1000);
    }

    for (token = 'S'; token.length <= 9; token += 'S') {
        addParseToken(token, parseMs);
    }
    // MOMENTS

    var getSetMillisecond = makeGetSet('Milliseconds', false);

    // FORMATTING

    addFormatToken('z',  0, 0, 'zoneAbbr');
    addFormatToken('zz', 0, 0, 'zoneName');

    // MOMENTS

    function getZoneAbbr () {
        return this._isUTC ? 'UTC' : '';
    }

    function getZoneName () {
        return this._isUTC ? 'Coordinated Universal Time' : '';
    }

    var momentPrototype__proto = Moment.prototype;

    momentPrototype__proto.add               = add_subtract__add;
    momentPrototype__proto.calendar          = moment_calendar__calendar;
    momentPrototype__proto.clone             = clone;
    momentPrototype__proto.diff              = diff;
    momentPrototype__proto.endOf             = endOf;
    momentPrototype__proto.format            = format;
    momentPrototype__proto.from              = from;
    momentPrototype__proto.fromNow           = fromNow;
    momentPrototype__proto.to                = to;
    momentPrototype__proto.toNow             = toNow;
    momentPrototype__proto.get               = stringGet;
    momentPrototype__proto.invalidAt         = invalidAt;
    momentPrototype__proto.isAfter           = isAfter;
    momentPrototype__proto.isBefore          = isBefore;
    momentPrototype__proto.isBetween         = isBetween;
    momentPrototype__proto.isSame            = isSame;
    momentPrototype__proto.isSameOrAfter     = isSameOrAfter;
    momentPrototype__proto.isSameOrBefore    = isSameOrBefore;
    momentPrototype__proto.isValid           = moment_valid__isValid;
    momentPrototype__proto.lang              = lang;
    momentPrototype__proto.locale            = locale;
    momentPrototype__proto.localeData        = localeData;
    momentPrototype__proto.max               = prototypeMax;
    momentPrototype__proto.min               = prototypeMin;
    momentPrototype__proto.parsingFlags      = parsingFlags;
    momentPrototype__proto.set               = stringSet;
    momentPrototype__proto.startOf           = startOf;
    momentPrototype__proto.subtract          = add_subtract__subtract;
    momentPrototype__proto.toArray           = toArray;
    momentPrototype__proto.toObject          = toObject;
    momentPrototype__proto.toDate            = toDate;
    momentPrototype__proto.toISOString       = moment_format__toISOString;
    momentPrototype__proto.toJSON            = toJSON;
    momentPrototype__proto.toString          = toString;
    momentPrototype__proto.unix              = unix;
    momentPrototype__proto.valueOf           = to_type__valueOf;
    momentPrototype__proto.creationData      = creationData;

    // Year
    momentPrototype__proto.year       = getSetYear;
    momentPrototype__proto.isLeapYear = getIsLeapYear;

    // Week Year
    momentPrototype__proto.weekYear    = getSetWeekYear;
    momentPrototype__proto.isoWeekYear = getSetISOWeekYear;

    // Quarter
    momentPrototype__proto.quarter = momentPrototype__proto.quarters = getSetQuarter;

    // Month
    momentPrototype__proto.month       = getSetMonth;
    momentPrototype__proto.daysInMonth = getDaysInMonth;

    // Week
    momentPrototype__proto.week           = momentPrototype__proto.weeks        = getSetWeek;
    momentPrototype__proto.isoWeek        = momentPrototype__proto.isoWeeks     = getSetISOWeek;
    momentPrototype__proto.weeksInYear    = getWeeksInYear;
    momentPrototype__proto.isoWeeksInYear = getISOWeeksInYear;

    // Day
    momentPrototype__proto.date       = getSetDayOfMonth;
    momentPrototype__proto.day        = momentPrototype__proto.days             = getSetDayOfWeek;
    momentPrototype__proto.weekday    = getSetLocaleDayOfWeek;
    momentPrototype__proto.isoWeekday = getSetISODayOfWeek;
    momentPrototype__proto.dayOfYear  = getSetDayOfYear;

    // Hour
    momentPrototype__proto.hour = momentPrototype__proto.hours = getSetHour;

    // Minute
    momentPrototype__proto.minute = momentPrototype__proto.minutes = getSetMinute;

    // Second
    momentPrototype__proto.second = momentPrototype__proto.seconds = getSetSecond;

    // Millisecond
    momentPrototype__proto.millisecond = momentPrototype__proto.milliseconds = getSetMillisecond;

    // Offset
    momentPrototype__proto.utcOffset            = getSetOffset;
    momentPrototype__proto.utc                  = setOffsetToUTC;
    momentPrototype__proto.local                = setOffsetToLocal;
    momentPrototype__proto.parseZone            = setOffsetToParsedOffset;
    momentPrototype__proto.hasAlignedHourOffset = hasAlignedHourOffset;
    momentPrototype__proto.isDST                = isDaylightSavingTime;
    momentPrototype__proto.isLocal              = isLocal;
    momentPrototype__proto.isUtcOffset          = isUtcOffset;
    momentPrototype__proto.isUtc                = isUtc;
    momentPrototype__proto.isUTC                = isUtc;

    // Timezone
    momentPrototype__proto.zoneAbbr = getZoneAbbr;
    momentPrototype__proto.zoneName = getZoneName;

    // Deprecations
    momentPrototype__proto.dates  = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth);
    momentPrototype__proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth);
    momentPrototype__proto.years  = deprecate('years accessor is deprecated. Use year instead', getSetYear);
    momentPrototype__proto.zone   = deprecate('moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/', getSetZone);
    momentPrototype__proto.isDSTShifted = deprecate('isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information', isDaylightSavingTimeShifted);

    var momentPrototype = momentPrototype__proto;

    function moment__createUnix (input) {
        return local__createLocal(input * 1000);
    }

    function moment__createInZone () {
        return local__createLocal.apply(null, arguments).parseZone();
    }

    function preParsePostFormat (string) {
        return string;
    }

    var prototype__proto = Locale.prototype;

    prototype__proto.calendar        = locale_calendar__calendar;
    prototype__proto.longDateFormat  = longDateFormat;
    prototype__proto.invalidDate     = invalidDate;
    prototype__proto.ordinal         = ordinal;
    prototype__proto.preparse        = preParsePostFormat;
    prototype__proto.postformat      = preParsePostFormat;
    prototype__proto.relativeTime    = relative__relativeTime;
    prototype__proto.pastFuture      = pastFuture;
    prototype__proto.set             = locale_set__set;

    // Month
    prototype__proto.months            =        localeMonths;
    prototype__proto.monthsShort       =        localeMonthsShort;
    prototype__proto.monthsParse       =        localeMonthsParse;
    prototype__proto.monthsRegex       = monthsRegex;
    prototype__proto.monthsShortRegex  = monthsShortRegex;

    // Week
    prototype__proto.week = localeWeek;
    prototype__proto.firstDayOfYear = localeFirstDayOfYear;
    prototype__proto.firstDayOfWeek = localeFirstDayOfWeek;

    // Day of Week
    prototype__proto.weekdays       =        localeWeekdays;
    prototype__proto.weekdaysMin    =        localeWeekdaysMin;
    prototype__proto.weekdaysShort  =        localeWeekdaysShort;
    prototype__proto.weekdaysParse  =        localeWeekdaysParse;

    prototype__proto.weekdaysRegex       =        weekdaysRegex;
    prototype__proto.weekdaysShortRegex  =        weekdaysShortRegex;
    prototype__proto.weekdaysMinRegex    =        weekdaysMinRegex;

    // Hours
    prototype__proto.isPM = localeIsPM;
    prototype__proto.meridiem = localeMeridiem;

    function lists__get (format, index, field, setter) {
        var locale = locale_locales__getLocale();
        var utc = create_utc__createUTC().set(setter, index);
        return locale[field](utc, format);
    }

    function listMonthsImpl (format, index, field) {
        if (typeof format === 'number') {
            index = format;
            format = undefined;
        }

        format = format || '';

        if (index != null) {
            return lists__get(format, index, field, 'month');
        }

        var i;
        var out = [];
        for (i = 0; i < 12; i++) {
            out[i] = lists__get(format, i, field, 'month');
        }
        return out;
    }

    // ()
    // (5)
    // (fmt, 5)
    // (fmt)
    // (true)
    // (true, 5)
    // (true, fmt, 5)
    // (true, fmt)
    function listWeekdaysImpl (localeSorted, format, index, field) {
        if (typeof localeSorted === 'boolean') {
            if (typeof format === 'number') {
                index = format;
                format = undefined;
            }

            format = format || '';
        } else {
            format = localeSorted;
            index = format;
            localeSorted = false;

            if (typeof format === 'number') {
                index = format;
                format = undefined;
            }

            format = format || '';
        }

        var locale = locale_locales__getLocale(),
            shift = localeSorted ? locale._week.dow : 0;

        if (index != null) {
            return lists__get(format, (index + shift) % 7, field, 'day');
        }

        var i;
        var out = [];
        for (i = 0; i < 7; i++) {
            out[i] = lists__get(format, (i + shift) % 7, field, 'day');
        }
        return out;
    }

    function lists__listMonths (format, index) {
        return listMonthsImpl(format, index, 'months');
    }

    function lists__listMonthsShort (format, index) {
        return listMonthsImpl(format, index, 'monthsShort');
    }

    function lists__listWeekdays (localeSorted, format, index) {
        return listWeekdaysImpl(localeSorted, format, index, 'weekdays');
    }

    function lists__listWeekdaysShort (localeSorted, format, index) {
        return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort');
    }

    function lists__listWeekdaysMin (localeSorted, format, index) {
        return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin');
    }

    locale_locales__getSetGlobalLocale('en', {
        ordinalParse: /\d{1,2}(th|st|nd|rd)/,
        ordinal : function (number) {
            var b = number % 10,
                output = (toInt(number % 100 / 10) === 1) ? 'th' :
                (b === 1) ? 'st' :
                (b === 2) ? 'nd' :
                (b === 3) ? 'rd' : 'th';
            return number + output;
        }
    });

    // Side effect imports
    utils_hooks__hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', locale_locales__getSetGlobalLocale);
    utils_hooks__hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', locale_locales__getLocale);

    var mathAbs = Math.abs;

    function duration_abs__abs () {
        var data           = this._data;

        this._milliseconds = mathAbs(this._milliseconds);
        this._days         = mathAbs(this._days);
        this._months       = mathAbs(this._months);

        data.milliseconds  = mathAbs(data.milliseconds);
        data.seconds       = mathAbs(data.seconds);
        data.minutes       = mathAbs(data.minutes);
        data.hours         = mathAbs(data.hours);
        data.months        = mathAbs(data.months);
        data.years         = mathAbs(data.years);

        return this;
    }

    function duration_add_subtract__addSubtract (duration, input, value, direction) {
        var other = create__createDuration(input, value);

        duration._milliseconds += direction * other._milliseconds;
        duration._days         += direction * other._days;
        duration._months       += direction * other._months;

        return duration._bubble();
    }

    // supports only 2.0-style add(1, 's') or add(duration)
    function duration_add_subtract__add (input, value) {
        return duration_add_subtract__addSubtract(this, input, value, 1);
    }

    // supports only 2.0-style subtract(1, 's') or subtract(duration)
    function duration_add_subtract__subtract (input, value) {
        return duration_add_subtract__addSubtract(this, input, value, -1);
    }

    function absCeil (number) {
        if (number < 0) {
            return Math.floor(number);
        } else {
            return Math.ceil(number);
        }
    }

    function bubble () {
        var milliseconds = this._milliseconds;
        var days         = this._days;
        var months       = this._months;
        var data         = this._data;
        var seconds, minutes, hours, years, monthsFromDays;

        // if we have a mix of positive and negative values, bubble down first
        // check: https://github.com/moment/moment/issues/2166
        if (!((milliseconds >= 0 && days >= 0 && months >= 0) ||
                (milliseconds <= 0 && days <= 0 && months <= 0))) {
            milliseconds += absCeil(monthsToDays(months) + days) * 864e5;
            days = 0;
            months = 0;
        }

        // The following code bubbles up values, see the tests for
        // examples of what that means.
        data.milliseconds = milliseconds % 1000;

        seconds           = absFloor(milliseconds / 1000);
        data.seconds      = seconds % 60;

        minutes           = absFloor(seconds / 60);
        data.minutes      = minutes % 60;

        hours             = absFloor(minutes / 60);
        data.hours        = hours % 24;

        days += absFloor(hours / 24);

        // convert days to months
        monthsFromDays = absFloor(daysToMonths(days));
        months += monthsFromDays;
        days -= absCeil(monthsToDays(monthsFromDays));

        // 12 months -> 1 year
        years = absFloor(months / 12);
        months %= 12;

        data.days   = days;
        data.months = months;
        data.years  = years;

        return this;
    }

    function daysToMonths (days) {
        // 400 years have 146097 days (taking into account leap year rules)
        // 400 years have 12 months === 4800
        return days * 4800 / 146097;
    }

    function monthsToDays (months) {
        // the reverse of daysToMonths
        return months * 146097 / 4800;
    }

    function as (units) {
        var days;
        var months;
        var milliseconds = this._milliseconds;

        units = normalizeUnits(units);

        if (units === 'month' || units === 'year') {
            days   = this._days   + milliseconds / 864e5;
            months = this._months + daysToMonths(days);
            return units === 'month' ? months : months / 12;
        } else {
            // handle milliseconds separately because of floating point math errors (issue #1867)
            days = this._days + Math.round(monthsToDays(this._months));
            switch (units) {
                case 'week'   : return days / 7     + milliseconds / 6048e5;
                case 'day'    : return days         + milliseconds / 864e5;
                case 'hour'   : return days * 24    + milliseconds / 36e5;
                case 'minute' : return days * 1440  + milliseconds / 6e4;
                case 'second' : return days * 86400 + milliseconds / 1000;
                // Math.floor prevents floating point math errors here
                case 'millisecond': return Math.floor(days * 864e5) + milliseconds;
                default: throw new Error('Unknown unit ' + units);
            }
        }
    }

    // TODO: Use this.as('ms')?
    function duration_as__valueOf () {
        return (
            this._milliseconds +
            this._days * 864e5 +
            (this._months % 12) * 2592e6 +
            toInt(this._months / 12) * 31536e6
        );
    }

    function makeAs (alias) {
        return function () {
            return this.as(alias);
        };
    }

    var asMilliseconds = makeAs('ms');
    var asSeconds      = makeAs('s');
    var asMinutes      = makeAs('m');
    var asHours        = makeAs('h');
    var asDays         = makeAs('d');
    var asWeeks        = makeAs('w');
    var asMonths       = makeAs('M');
    var asYears        = makeAs('y');

    function duration_get__get (units) {
        units = normalizeUnits(units);
        return this[units + 's']();
    }

    function makeGetter(name) {
        return function () {
            return this._data[name];
        };
    }

    var milliseconds = makeGetter('milliseconds');
    var seconds      = makeGetter('seconds');
    var minutes      = makeGetter('minutes');
    var hours        = makeGetter('hours');
    var days         = makeGetter('days');
    var months       = makeGetter('months');
    var years        = makeGetter('years');

    function weeks () {
        return absFloor(this.days() / 7);
    }

    var round = Math.round;
    var thresholds = {
        s: 45,  // seconds to minute
        m: 45,  // minutes to hour
        h: 22,  // hours to day
        d: 26,  // days to month
        M: 11   // months to year
    };

    // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
    function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
        return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
    }

    function duration_humanize__relativeTime (posNegDuration, withoutSuffix, locale) {
        var duration = create__createDuration(posNegDuration).abs();
        var seconds  = round(duration.as('s'));
        var minutes  = round(duration.as('m'));
        var hours    = round(duration.as('h'));
        var days     = round(duration.as('d'));
        var months   = round(duration.as('M'));
        var years    = round(duration.as('y'));

        var a = seconds < thresholds.s && ['s', seconds]  ||
                minutes <= 1           && ['m']           ||
                minutes < thresholds.m && ['mm', minutes] ||
                hours   <= 1           && ['h']           ||
                hours   < thresholds.h && ['hh', hours]   ||
                days    <= 1           && ['d']           ||
                days    < thresholds.d && ['dd', days]    ||
                months  <= 1           && ['M']           ||
                months  < thresholds.M && ['MM', months]  ||
                years   <= 1           && ['y']           || ['yy', years];

        a[2] = withoutSuffix;
        a[3] = +posNegDuration > 0;
        a[4] = locale;
        return substituteTimeAgo.apply(null, a);
    }

    // This function allows you to set the rounding function for relative time strings
    function duration_humanize__getSetRelativeTimeRounding (roundingFunction) {
        if (roundingFunction === undefined) {
            return round;
        }
        if (typeof(roundingFunction) === 'function') {
            round = roundingFunction;
            return true;
        }
        return false;
    }

    // This function allows you to set a threshold for relative time strings
    function duration_humanize__getSetRelativeTimeThreshold (threshold, limit) {
        if (thresholds[threshold] === undefined) {
            return false;
        }
        if (limit === undefined) {
            return thresholds[threshold];
        }
        thresholds[threshold] = limit;
        return true;
    }

    function humanize (withSuffix) {
        var locale = this.localeData();
        var output = duration_humanize__relativeTime(this, !withSuffix, locale);

        if (withSuffix) {
            output = locale.pastFuture(+this, output);
        }

        return locale.postformat(output);
    }

    var iso_string__abs = Math.abs;

    function iso_string__toISOString() {
        // for ISO strings we do not use the normal bubbling rules:
        //  * milliseconds bubble up until they become hours
        //  * days do not bubble at all
        //  * months bubble up until they become years
        // This is because there is no context-free conversion between hours and days
        // (think of clock changes)
        // and also not between days and months (28-31 days per month)
        var seconds = iso_string__abs(this._milliseconds) / 1000;
        var days         = iso_string__abs(this._days);
        var months       = iso_string__abs(this._months);
        var minutes, hours, years;

        // 3600 seconds -> 60 minutes -> 1 hour
        minutes           = absFloor(seconds / 60);
        hours             = absFloor(minutes / 60);
        seconds %= 60;
        minutes %= 60;

        // 12 months -> 1 year
        years  = absFloor(months / 12);
        months %= 12;


        // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
        var Y = years;
        var M = months;
        var D = days;
        var h = hours;
        var m = minutes;
        var s = seconds;
        var total = this.asSeconds();

        if (!total) {
            // this is the same as C#'s (Noda) and python (isodate)...
            // but not other JS (goog.date)
            return 'P0D';
        }

        return (total < 0 ? '-' : '') +
            'P' +
            (Y ? Y + 'Y' : '') +
            (M ? M + 'M' : '') +
            (D ? D + 'D' : '') +
            ((h || m || s) ? 'T' : '') +
            (h ? h + 'H' : '') +
            (m ? m + 'M' : '') +
            (s ? s + 'S' : '');
    }

    var duration_prototype__proto = Duration.prototype;

    duration_prototype__proto.abs            = duration_abs__abs;
    duration_prototype__proto.add            = duration_add_subtract__add;
    duration_prototype__proto.subtract       = duration_add_subtract__subtract;
    duration_prototype__proto.as             = as;
    duration_prototype__proto.asMilliseconds = asMilliseconds;
    duration_prototype__proto.asSeconds      = asSeconds;
    duration_prototype__proto.asMinutes      = asMinutes;
    duration_prototype__proto.asHours        = asHours;
    duration_prototype__proto.asDays         = asDays;
    duration_prototype__proto.asWeeks        = asWeeks;
    duration_prototype__proto.asMonths       = asMonths;
    duration_prototype__proto.asYears        = asYears;
    duration_prototype__proto.valueOf        = duration_as__valueOf;
    duration_prototype__proto._bubble        = bubble;
    duration_prototype__proto.get            = duration_get__get;
    duration_prototype__proto.milliseconds   = milliseconds;
    duration_prototype__proto.seconds        = seconds;
    duration_prototype__proto.minutes        = minutes;
    duration_prototype__proto.hours          = hours;
    duration_prototype__proto.days           = days;
    duration_prototype__proto.weeks          = weeks;
    duration_prototype__proto.months         = months;
    duration_prototype__proto.years          = years;
    duration_prototype__proto.humanize       = humanize;
    duration_prototype__proto.toISOString    = iso_string__toISOString;
    duration_prototype__proto.toString       = iso_string__toISOString;
    duration_prototype__proto.toJSON         = iso_string__toISOString;
    duration_prototype__proto.locale         = locale;
    duration_prototype__proto.localeData     = localeData;

    // Deprecations
    duration_prototype__proto.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', iso_string__toISOString);
    duration_prototype__proto.lang = lang;

    // Side effect imports

    // FORMATTING

    addFormatToken('X', 0, 0, 'unix');
    addFormatToken('x', 0, 0, 'valueOf');

    // PARSING

    addRegexToken('x', matchSigned);
    addRegexToken('X', matchTimestamp);
    addParseToken('X', function (input, array, config) {
        config._d = new Date(parseFloat(input, 10) * 1000);
    });
    addParseToken('x', function (input, array, config) {
        config._d = new Date(toInt(input));
    });

    // Side effect imports


    utils_hooks__hooks.version = '2.15.2';

    setHookCallback(local__createLocal);

    utils_hooks__hooks.fn                    = momentPrototype;
    utils_hooks__hooks.min                   = min;
    utils_hooks__hooks.max                   = max;
    utils_hooks__hooks.now                   = now;
    utils_hooks__hooks.utc                   = create_utc__createUTC;
    utils_hooks__hooks.unix                  = moment__createUnix;
    utils_hooks__hooks.months                = lists__listMonths;
    utils_hooks__hooks.isDate                = isDate;
    utils_hooks__hooks.locale                = locale_locales__getSetGlobalLocale;
    utils_hooks__hooks.invalid               = valid__createInvalid;
    utils_hooks__hooks.duration              = create__createDuration;
    utils_hooks__hooks.isMoment              = isMoment;
    utils_hooks__hooks.weekdays              = lists__listWeekdays;
    utils_hooks__hooks.parseZone             = moment__createInZone;
    utils_hooks__hooks.localeData            = locale_locales__getLocale;
    utils_hooks__hooks.isDuration            = isDuration;
    utils_hooks__hooks.monthsShort           = lists__listMonthsShort;
    utils_hooks__hooks.weekdaysMin           = lists__listWeekdaysMin;
    utils_hooks__hooks.defineLocale          = defineLocale;
    utils_hooks__hooks.updateLocale          = updateLocale;
    utils_hooks__hooks.locales               = locale_locales__listLocales;
    utils_hooks__hooks.weekdaysShort         = lists__listWeekdaysShort;
    utils_hooks__hooks.normalizeUnits        = normalizeUnits;
    utils_hooks__hooks.relativeTimeRounding = duration_humanize__getSetRelativeTimeRounding;
    utils_hooks__hooks.relativeTimeThreshold = duration_humanize__getSetRelativeTimeThreshold;
    utils_hooks__hooks.calendarFormat        = getCalendarFormat;
    utils_hooks__hooks.prototype             = momentPrototype;

    var _moment = utils_hooks__hooks;

    return _moment;

}));;
(function (d, s, id) {
    if (d.getElementById(id + s)) return;
    var js, t = d.getElementsByTagName(s)[0];
    js = d.createElement(s);
    js.id = id + s;
    js.onload = function () { HatchRequest.init() };
    js.src = 'https://cdn.gethatch.com/hatch-buy-now-request-1.0.stable.js';
    t.parentNode.insertBefore(js, t);
}(document, 'script', 'hatch-buy-now-request-'));

//disclaimer hack
const dgbnb = document.querySelectorAll('[data-gh-buy-now-button]');

if (dgbnb.length > 0) {
    const countryCode = dgbnb[0].getAttribute('data-gh-country-code');
    const AU_h_disclaimer_text = 'The retailers shown are authorised Canon Australia retailers. This is not an exhaustive list of where you can buy the product. By clicking on a retailer link you will leave the Canon website and will no longer be bound by Canon\'s terms and conditions or privacy policy.Canon is not responsible for the content, accuracy, terms and conditions or privacy policy of retailer websites.Stock availability and prices may vary, so please check with the retailer directly for up to date information.<br><br><br>';
    const NZ_h_disclaimer_text = 'The retailers shown are authorised Canon New Zealand retailers. This is not an exhaustive list of where you can buy the product. By clicking on a retailer link you will leave the Canon website and will no longer be bound by Canon\'s terms and conditions or privacy policy.Canon is not responsible for the content, accuracy, terms and conditions or privacy policy of retailer websites.Stock availability and prices may vary, so please check with the retailer directly for up to date information.<br><br><br>';

    var discalaimer_el = document.createElement('div');
    if (countryCode === 'NZ') {
        discalaimer_el.innerHTML = NZ_h_disclaimer_text;
    }
    else {
        discalaimer_el.innerHTML = AU_h_disclaimer_text;
    }
    discalaimer_el.style.cssText = 'border: 1px solid #e0e0e0;bottom: 23px;height:auto;align-items: center;line-height:100%;background-color: #f5f5f5;width: 100%;text-align: center;color: #a0a0a0;font-size: 12px;margin-right: 3px;font-family: "Proxima Nova", Arial, Helvetica, sans-serif !important';

    dgbnb.forEach(function (v, i, o) {
        v.addEventListener("click", function (e) {
            setTimeout(() => {
                const hw = document.querySelectorAll('[class^="hatch-widget"]');
                if (hw.length > 5) {
                    const footer_el = hw[hw.length - 5];
                    footer_el.parentNode.insertBefore(discalaimer_el, footer_el);
                }
                else {
                    $(dgbnb[1]).trigger('click');
                }

            }, 500);

        }, false);
    });

}
;
/*! Lazy Load 1.9.1 - MIT license - Copyright 2010-2013 Mika Tuupola */
!function(a,b,c,d){var e=a(b);a.fn.lazyload=function(f){function g(){var b=0;i.each(function(){var c=a(this);if(!j.skip_invisible||c.is(":visible"))if(a.abovethetop(this,j)||a.leftofbegin(this,j));else if(a.belowthefold(this,j)||a.rightoffold(this,j)){if(++b>j.failure_limit)return!1}else c.trigger("appear"),b=0})}var h,i=this,j={threshold:0,failure_limit:0,event:"scroll",effect:"show",container:b,data_attribute:"original",skip_invisible:!0,appear:null,load:null,placeholder:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC"};return f&&(d!==f.failurelimit&&(f.failure_limit=f.failurelimit,delete f.failurelimit),d!==f.effectspeed&&(f.effect_speed=f.effectspeed,delete f.effectspeed),a.extend(j,f)),h=j.container===d||j.container===b?e:a(j.container),0===j.event.indexOf("scroll")&&h.bind(j.event,function(){return g()}),this.each(function(){var b=this,c=a(b);b.loaded=!1,(c.attr("src")===d||c.attr("src")===!1)&&c.is("img")&&c.attr("src",j.placeholder),c.one("appear",function(){if(!this.loaded){if(j.appear){var d=i.length;j.appear.call(b,d,j)}a("<img />").bind("load",function(){var d=c.attr("data-"+j.data_attribute);c.hide(),c.is("img")?c.attr("src",d):c.css("background-image","url('"+d+"')"),c[j.effect](j.effect_speed),b.loaded=!0;var e=a.grep(i,function(a){return!a.loaded});if(i=a(e),j.load){var f=i.length;j.load.call(b,f,j)}}).attr("src",c.attr("data-"+j.data_attribute))}}),0!==j.event.indexOf("scroll")&&c.bind(j.event,function(){b.loaded||c.trigger("appear")})}),e.bind("resize",function(){g()}),/(?:iphone|ipod|ipad).*os 5/gi.test(navigator.appVersion)&&e.bind("pageshow",function(b){b.originalEvent&&b.originalEvent.persisted&&i.each(function(){a(this).trigger("appear")})}),a(c).ready(function(){g()}),this},a.belowthefold=function(c,f){var g;return g=f.container===d||f.container===b?(b.innerHeight?b.innerHeight:e.height())+e.scrollTop():a(f.container).offset().top+a(f.container).height(),g<=a(c).offset().top-f.threshold},a.rightoffold=function(c,f){var g;return g=f.container===d||f.container===b?e.width()+e.scrollLeft():a(f.container).offset().left+a(f.container).width(),g<=a(c).offset().left-f.threshold},a.abovethetop=function(c,f){var g;return g=f.container===d||f.container===b?e.scrollTop():a(f.container).offset().top,g>=a(c).offset().top+f.threshold+a(c).height()},a.leftofbegin=function(c,f){var g;return g=f.container===d||f.container===b?e.scrollLeft():a(f.container).offset().left,g>=a(c).offset().left+f.threshold+a(c).width()},a.inviewport=function(b,c){return!(a.rightoffold(b,c)||a.leftofbegin(b,c)||a.belowthefold(b,c)||a.abovethetop(b,c))},a.extend(a.expr[":"],{"below-the-fold":function(b){return a.belowthefold(b,{threshold:0})},"above-the-top":function(b){return!a.belowthefold(b,{threshold:0})},"right-of-screen":function(b){return a.rightoffold(b,{threshold:0})},"left-of-screen":function(b){return!a.rightoffold(b,{threshold:0})},"in-viewport":function(b){return a.inviewport(b,{threshold:0})},"above-the-fold":function(b){return!a.belowthefold(b,{threshold:0})},"right-of-fold":function(b){return a.rightoffold(b,{threshold:0})},"left-of-fold":function(b){return!a.rightoffold(b,{threshold:0})}})}(jQuery,window,document);;
!function(){"use strict";function e(n){return"undefined"==typeof this||Object.getPrototypeOf(this)!==e.prototype?new e(n):(O=this,O.version="3.3.2",O.tools=new E,O.isSupported()?(O.tools.extend(O.defaults,n||{}),O.defaults.container=t(O.defaults),O.store={elements:{},containers:[]},O.sequences={},O.history=[],O.uid=0,O.initialized=!1):"undefined"!=typeof console&&null!==console,O)}function t(e){if(e&&e.container){if("string"==typeof e.container)return window.document.documentElement.querySelector(e.container);if(O.tools.isNode(e.container))return e.container}return O.defaults.container}function n(e,t){return"string"==typeof e?Array.prototype.slice.call(t.querySelectorAll(e)):O.tools.isNode(e)?[e]:O.tools.isNodeList(e)?Array.prototype.slice.call(e):[]}function i(){return++O.uid}function o(e,t,n){t.container&&(t.container=n),e.config?e.config=O.tools.extendClone(e.config,t):e.config=O.tools.extendClone(O.defaults,t),"top"===e.config.origin||"bottom"===e.config.origin?e.config.axis="Y":e.config.axis="X"}function r(e){var t=window.getComputedStyle(e.domEl);e.styles||(e.styles={transition:{},transform:{},computed:{}},e.styles.inline=e.domEl.getAttribute("style")||"",e.styles.inline+="; visibility: visible; ",e.styles.computed.opacity=t.opacity,t.transition&&"all 0s ease 0s"!==t.transition?e.styles.computed.transition=t.transition+", ":e.styles.computed.transition=""),e.styles.transition.instant=s(e,0),e.styles.transition.delayed=s(e,e.config.delay),e.styles.transform.initial=" -webkit-transform:",e.styles.transform.target=" -webkit-transform:",a(e),e.styles.transform.initial+="transform:",e.styles.transform.target+="transform:",a(e)}function s(e,t){var n=e.config;return"-webkit-transition: "+e.styles.computed.transition+"-webkit-transform "+n.duration/1e3+"s "+n.easing+" "+t/1e3+"s, opacity "+n.duration/1e3+"s "+n.easing+" "+t/1e3+"s; transition: "+e.styles.computed.transition+"transform "+n.duration/1e3+"s "+n.easing+" "+t/1e3+"s, opacity "+n.duration/1e3+"s "+n.easing+" "+t/1e3+"s; "}function a(e){var t,n=e.config,i=e.styles.transform;t="top"===n.origin||"left"===n.origin?/^-/.test(n.distance)?n.distance.substr(1):"-"+n.distance:n.distance,parseInt(n.distance)&&(i.initial+=" translate"+n.axis+"("+t+")",i.target+=" translate"+n.axis+"(0)"),n.scale&&(i.initial+=" scale("+n.scale+")",i.target+=" scale(1)"),n.rotate.x&&(i.initial+=" rotateX("+n.rotate.x+"deg)",i.target+=" rotateX(0)"),n.rotate.y&&(i.initial+=" rotateY("+n.rotate.y+"deg)",i.target+=" rotateY(0)"),n.rotate.z&&(i.initial+=" rotateZ("+n.rotate.z+"deg)",i.target+=" rotateZ(0)"),i.initial+="; opacity: "+n.opacity+";",i.target+="; opacity: "+e.styles.computed.opacity+";"}function l(e){var t=e.config.container;t&&O.store.containers.indexOf(t)===-1&&O.store.containers.push(e.config.container),O.store.elements[e.id]=e}function c(e,t,n){var i={target:e,config:t,interval:n};O.history.push(i)}function f(){if(O.isSupported()){y();for(var e=0;e<O.store.containers.length;e++)O.store.containers[e].addEventListener("scroll",d),O.store.containers[e].addEventListener("resize",d);O.initialized||(window.addEventListener("scroll",d),window.addEventListener("resize",d),O.initialized=!0)}return O}function d(){T(y)}function u(){var e,t,n,i;O.tools.forOwn(O.sequences,function(o){i=O.sequences[o],e=!1;for(var r=0;r<i.elemIds.length;r++)n=i.elemIds[r],t=O.store.elements[n],q(t)&&!e&&(e=!0);i.active=e})}function y(){var e,t;u(),O.tools.forOwn(O.store.elements,function(n){t=O.store.elements[n],e=w(t),g(t)?(t.config.beforeReveal(t.domEl),e?t.domEl.setAttribute("style",t.styles.inline+t.styles.transform.target+t.styles.transition.delayed):t.domEl.setAttribute("style",t.styles.inline+t.styles.transform.target+t.styles.transition.instant),p("reveal",t,e),t.revealing=!0,t.seen=!0,t.sequence&&m(t,e)):v(t)&&(t.config.beforeReset(t.domEl),t.domEl.setAttribute("style",t.styles.inline+t.styles.transform.initial+t.styles.transition.instant),p("reset",t),t.revealing=!1)})}function m(e,t){var n=0,i=0,o=O.sequences[e.sequence.id];o.blocked=!0,t&&"onload"===e.config.useDelay&&(i=e.config.delay),e.sequence.timer&&(n=Math.abs(e.sequence.timer.started-new Date),window.clearTimeout(e.sequence.timer)),e.sequence.timer={started:new Date},e.sequence.timer.clock=window.setTimeout(function(){o.blocked=!1,e.sequence.timer=null,d()},Math.abs(o.interval)+i-n)}function p(e,t,n){var i=0,o=0,r="after";switch(e){case"reveal":o=t.config.duration,n&&(o+=t.config.delay),r+="Reveal";break;case"reset":o=t.config.duration,r+="Reset"}t.timer&&(i=Math.abs(t.timer.started-new Date),window.clearTimeout(t.timer.clock)),t.timer={started:new Date},t.timer.clock=window.setTimeout(function(){t.config[r](t.domEl),t.timer=null},o-i)}function g(e){if(e.sequence){var t=O.sequences[e.sequence.id];return t.active&&!t.blocked&&!e.revealing&&!e.disabled}return q(e)&&!e.revealing&&!e.disabled}function w(e){var t=e.config.useDelay;return"always"===t||"onload"===t&&!O.initialized||"once"===t&&!e.seen}function v(e){if(e.sequence){var t=O.sequences[e.sequence.id];return!t.active&&e.config.reset&&e.revealing&&!e.disabled}return!q(e)&&e.config.reset&&e.revealing&&!e.disabled}function b(e){return{width:e.clientWidth,height:e.clientHeight}}function h(e){if(e&&e!==window.document.documentElement){var t=x(e);return{x:e.scrollLeft+t.left,y:e.scrollTop+t.top}}return{x:window.pageXOffset,y:window.pageYOffset}}function x(e){var t=0,n=0,i=e.offsetHeight,o=e.offsetWidth;do isNaN(e.offsetTop)||(t+=e.offsetTop),isNaN(e.offsetLeft)||(n+=e.offsetLeft),e=e.offsetParent;while(e);return{top:t,left:n,height:i,width:o}}function q(e){function t(){var t=c+a*s,n=f+l*s,i=d-a*s,y=u-l*s,m=r.y+e.config.viewOffset.top,p=r.x+e.config.viewOffset.left,g=r.y-e.config.viewOffset.bottom+o.height,w=r.x-e.config.viewOffset.right+o.width;return t<g&&i>m&&n>p&&y<w}function n(){return"fixed"===window.getComputedStyle(e.domEl).position}var i=x(e.domEl),o=b(e.config.container),r=h(e.config.container),s=e.config.viewFactor,a=i.height,l=i.width,c=i.top,f=i.left,d=c+a,u=f+l;return t()||n()}function E(){}var O,T;e.prototype.defaults={origin:"bottom",distance:"20px",duration:500,delay:0,rotate:{x:0,y:0,z:0},opacity:0,scale:.9,easing:"cubic-bezier(0.6, 0.2, 0.1, 1)",container:window.document.documentElement,mobile:!0,reset:!1,useDelay:"always",viewFactor:.2,viewOffset:{top:0,right:0,bottom:0,left:0},beforeReveal:function(e){},beforeReset:function(e){},afterReveal:function(e){},afterReset:function(e){}},e.prototype.isSupported=function(){var e=document.documentElement.style;return"WebkitTransition"in e&&"WebkitTransform"in e||"transition"in e&&"transform"in e},e.prototype.reveal=function(e,s,a,d){var u,y,m,p,g,w;if(void 0!==s&&"number"==typeof s?(a=s,s={}):void 0!==s&&null!==s||(s={}),u=t(s),y=n(e,u),!y.length)return O;a&&"number"==typeof a&&(w=i(),g=O.sequences[w]={id:w,interval:a,elemIds:[],active:!1});for(var v=0;v<y.length;v++)p=y[v].getAttribute("data-sr-id"),p?m=O.store.elements[p]:(m={id:i(),domEl:y[v],seen:!1,revealing:!1},m.domEl.setAttribute("data-sr-id",m.id)),g&&(m.sequence={id:g.id,index:g.elemIds.length},g.elemIds.push(m.id)),o(m,s,u),r(m),l(m),O.tools.isMobile()&&!m.config.mobile||!O.isSupported()?(m.domEl.setAttribute("style",m.styles.inline),m.disabled=!0):m.revealing||m.domEl.setAttribute("style",m.styles.inline+m.styles.transform.initial);return!d&&O.isSupported()&&(c(e,s,a),O.initTimeout&&window.clearTimeout(O.initTimeout),O.initTimeout=window.setTimeout(f,0)),O},e.prototype.sync=function(){if(O.history.length&&O.isSupported()){for(var e=0;e<O.history.length;e++){var t=O.history[e];O.reveal(t.target,t.config,t.interval,!0)}f()}return O},E.prototype.isObject=function(e){return null!==e&&"object"==typeof e&&e.constructor===Object},E.prototype.isNode=function(e){return"object"==typeof window.Node?e instanceof window.Node:e&&"object"==typeof e&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName},E.prototype.isNodeList=function(e){var t=Object.prototype.toString.call(e),n=/^\[object (HTMLCollection|NodeList|Object)\]$/;return"object"==typeof window.NodeList?e instanceof window.NodeList:e&&"object"==typeof e&&n.test(t)&&"number"==typeof e.length&&(0===e.length||this.isNode(e[0]))},E.prototype.forOwn=function(e,t){if(!this.isObject(e))throw new TypeError('Expected "object", but received "'+typeof e+'".');for(var n in e)e.hasOwnProperty(n)&&t(n)},E.prototype.extend=function(e,t){return this.forOwn(t,function(n){this.isObject(t[n])?(e[n]&&this.isObject(e[n])||(e[n]={}),this.extend(e[n],t[n])):e[n]=t[n]}.bind(this)),e},E.prototype.extendClone=function(e,t){return this.extend(this.extend({},e),t)},E.prototype.isMobile=function(){return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)},T=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||function(e){window.setTimeout(e,1e3/60)},"function"==typeof define&&"object"==typeof define.amd&&define.amd?define(function(){return e}):"undefined"!=typeof module&&module.exports?module.exports=e:window.ScrollReveal=e}();;
/*! lazysizes - v4.0.1 */
!function(a,b){var c=b(a,a.document);a.lazySizes=c,"object"==typeof module&&module.exports&&(module.exports=c)}(window,function(a,b){"use strict";if(b.getElementsByClassName){var c,d,e=b.documentElement,f=a.Date,g=a.HTMLPictureElement,h="addEventListener",i="getAttribute",j=a[h],k=a.setTimeout,l=a.requestAnimationFrame||k,m=a.requestIdleCallback,n=/^picture$/i,o=["load","error","lazyincluded","_lazyloaded"],p={},q=Array.prototype.forEach,r=function(a,b){return p[b]||(p[b]=new RegExp("(\\s|^)"+b+"(\\s|$)")),p[b].test(a[i]("class")||"")&&p[b]},s=function(a,b){r(a,b)||a.setAttribute("class",(a[i]("class")||"").trim()+" "+b)},t=function(a,b){var c;(c=r(a,b))&&a.setAttribute("class",(a[i]("class")||"").replace(c," "))},u=function(a,b,c){var d=c?h:"removeEventListener";c&&u(a,b),o.forEach(function(c){a[d](c,b)})},v=function(a,d,e,f,g){var h=b.createEvent("CustomEvent");return e||(e={}),e.instance=c,h.initCustomEvent(d,!f,!g,e),a.dispatchEvent(h),h},w=function(b,c){var e;!g&&(e=a.picturefill||d.pf)?e({reevaluate:!0,elements:[b]}):c&&c.src&&(b.src=c.src)},x=function(a,b){return(getComputedStyle(a,null)||{})[b]},y=function(a,b,c){for(c=c||a.offsetWidth;c<d.minSize&&b&&!a._lazysizesWidth;)c=b.offsetWidth,b=b.parentNode;return c},z=function(){var a,c,d=[],e=[],f=d,g=function(){var b=f;for(f=d.length?e:d,a=!0,c=!1;b.length;)b.shift()();a=!1},h=function(d,e){a&&!e?d.apply(this,arguments):(f.push(d),c||(c=!0,(b.hidden?k:l)(g)))};return h._lsFlush=g,h}(),A=function(a,b){return b?function(){z(a)}:function(){var b=this,c=arguments;z(function(){a.apply(b,c)})}},B=function(a){var b,c=0,e=125,g=d.ricTimeout,h=function(){b=!1,c=f.now(),a()},i=m&&d.ricTimeout?function(){m(h,{timeout:g}),g!==d.ricTimeout&&(g=d.ricTimeout)}:A(function(){k(h)},!0);return function(a){var d;(a=a===!0)&&(g=33),b||(b=!0,d=e-(f.now()-c),0>d&&(d=0),a||9>d&&m?i():k(i,d))}},C=function(a){var b,c,d=99,e=function(){b=null,a()},g=function(){var a=f.now()-c;d>a?k(g,d-a):(m||e)(e)};return function(){c=f.now(),b||(b=k(g,d))}};!function(){var b,c={lazyClass:"lazyload",loadedClass:"lazyloaded",loadingClass:"lazyloading",preloadClass:"lazypreload",errorClass:"lazyerror",autosizesClass:"lazyautosizes",srcAttr:"data-src",srcsetAttr:"data-srcset",sizesAttr:"data-sizes",minSize:40,customMedia:{},init:!0,expFactor:1.5,hFac:.8,loadMode:2,loadHidden:!0,ricTimeout:300};d=a.lazySizesConfig||a.lazysizesConfig||{};for(b in c)b in d||(d[b]=c[b]);a.lazySizesConfig=d,k(function(){d.init&&F()})}();var D=function(){var g,l,m,o,p,y,D,F,G,H,I,J,K,L,M=/^img$/i,N=/^iframe$/i,O="onscroll"in a&&!/glebot/.test(navigator.userAgent),P=0,Q=0,R=0,S=-1,T=function(a){R--,a&&a.target&&u(a.target,T),(!a||0>R||!a.target)&&(R=0)},U=function(a,c){var d,f=a,g="hidden"==x(b.body,"visibility")||"hidden"!=x(a,"visibility");for(F-=c,I+=c,G-=c,H+=c;g&&(f=f.offsetParent)&&f!=b.body&&f!=e;)g=(x(f,"opacity")||1)>0,g&&"visible"!=x(f,"overflow")&&(d=f.getBoundingClientRect(),g=H>d.left&&G<d.right&&I>d.top-1&&F<d.bottom+1);return g},V=function(){var a,f,h,j,k,m,n,p,q,r=c.elements;if((o=d.loadMode)&&8>R&&(a=r.length)){f=0,S++,null==K&&("expand"in d||(d.expand=e.clientHeight>500&&e.clientWidth>500?500:370),J=d.expand,K=J*d.expFactor),K>Q&&1>R&&S>2&&o>2&&!b.hidden?(Q=K,S=0):Q=o>1&&S>1&&6>R?J:P;for(;a>f;f++)if(r[f]&&!r[f]._lazyRace)if(O)if((p=r[f][i]("data-expand"))&&(m=1*p)||(m=Q),q!==m&&(y=innerWidth+m*L,D=innerHeight+m,n=-1*m,q=m),h=r[f].getBoundingClientRect(),(I=h.bottom)>=n&&(F=h.top)<=D&&(H=h.right)>=n*L&&(G=h.left)<=y&&(I||H||G||F)&&(d.loadHidden||"hidden"!=x(r[f],"visibility"))&&(l&&3>R&&!p&&(3>o||4>S)||U(r[f],m))){if(ba(r[f]),k=!0,R>9)break}else!k&&l&&!j&&4>R&&4>S&&o>2&&(g[0]||d.preloadAfterLoad)&&(g[0]||!p&&(I||H||G||F||"auto"!=r[f][i](d.sizesAttr)))&&(j=g[0]||r[f]);else ba(r[f]);j&&!k&&ba(j)}},W=B(V),X=function(a){s(a.target,d.loadedClass),t(a.target,d.loadingClass),u(a.target,Z),v(a.target,"lazyloaded")},Y=A(X),Z=function(a){Y({target:a.target})},$=function(a,b){try{a.contentWindow.location.replace(b)}catch(c){a.src=b}},_=function(a){var b,c=a[i](d.srcsetAttr);(b=d.customMedia[a[i]("data-media")||a[i]("media")])&&a.setAttribute("media",b),c&&a.setAttribute("srcset",c)},aa=A(function(a,b,c,e,f){var g,h,j,l,o,p;(o=v(a,"lazybeforeunveil",b)).defaultPrevented||(e&&(c?s(a,d.autosizesClass):a.setAttribute("sizes",e)),h=a[i](d.srcsetAttr),g=a[i](d.srcAttr),f&&(j=a.parentNode,l=j&&n.test(j.nodeName||"")),p=b.firesLoad||"src"in a&&(h||g||l),o={target:a},p&&(u(a,T,!0),clearTimeout(m),m=k(T,2500),s(a,d.loadingClass),u(a,Z,!0)),l&&q.call(j.getElementsByTagName("source"),_),h?a.setAttribute("srcset",h):g&&!l&&(N.test(a.nodeName)?$(a,g):a.src=g),f&&(h||l)&&w(a,{src:g})),a._lazyRace&&delete a._lazyRace,t(a,d.lazyClass),z(function(){(!p||a.complete&&a.naturalWidth>1)&&(p?T(o):R--,X(o))},!0)}),ba=function(a){var b,c=M.test(a.nodeName),e=c&&(a[i](d.sizesAttr)||a[i]("sizes")),f="auto"==e;(!f&&l||!c||!a[i]("src")&&!a.srcset||a.complete||r(a,d.errorClass)||!r(a,d.lazyClass))&&(b=v(a,"lazyunveilread").detail,f&&E.updateElem(a,!0,a.offsetWidth),a._lazyRace=!0,R++,aa(a,b,f,e,c))},ca=function(){if(!l){if(f.now()-p<999)return void k(ca,999);var a=C(function(){d.loadMode=3,W()});l=!0,d.loadMode=3,W(),j("scroll",function(){3==d.loadMode&&(d.loadMode=2),a()},!0)}};return{_:function(){p=f.now(),c.elements=b.getElementsByClassName(d.lazyClass),g=b.getElementsByClassName(d.lazyClass+" "+d.preloadClass),L=d.hFac,j("scroll",W,!0),j("resize",W,!0),a.MutationObserver?new MutationObserver(W).observe(e,{childList:!0,subtree:!0,attributes:!0}):(e[h]("DOMNodeInserted",W,!0),e[h]("DOMAttrModified",W,!0),setInterval(W,999)),j("hashchange",W,!0),["focus","mouseover","click","load","transitionend","animationend","webkitAnimationEnd"].forEach(function(a){b[h](a,W,!0)}),/d$|^c/.test(b.readyState)?ca():(j("load",ca),b[h]("DOMContentLoaded",W),k(ca,2e4)),c.elements.length?(V(),z._lsFlush()):W()},checkElems:W,unveil:ba}}(),E=function(){var a,c=A(function(a,b,c,d){var e,f,g;if(a._lazysizesWidth=d,d+="px",a.setAttribute("sizes",d),n.test(b.nodeName||""))for(e=b.getElementsByTagName("source"),f=0,g=e.length;g>f;f++)e[f].setAttribute("sizes",d);c.detail.dataAttr||w(a,c.detail)}),e=function(a,b,d){var e,f=a.parentNode;f&&(d=y(a,f,d),e=v(a,"lazybeforesizes",{width:d,dataAttr:!!b}),e.defaultPrevented||(d=e.detail.width,d&&d!==a._lazysizesWidth&&c(a,f,e,d)))},f=function(){var b,c=a.length;if(c)for(b=0;c>b;b++)e(a[b])},g=C(f);return{_:function(){a=b.getElementsByClassName(d.autosizesClass),j("resize",g)},checkElems:g,updateElem:e}}(),F=function(){F.i||(F.i=!0,E._(),D._())};return c={cfg:d,autoSizer:E,loader:D,init:F,uP:w,aC:s,rC:t,hC:r,fire:v,gW:y,rAF:z}}});;
/* =============================================================
 * bootstrap3-typeahead.js v4.0.2
 * https://github.com/bassjobsen/Bootstrap-3-Typeahead
 * =============================================================
 * Original written by @mdo and @fat
 * =============================================================
 * Copyright 2014 Bass Jobsen @bassjobsen
 *
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============================================================ */


(function (root, factory) {

    'use strict';

    // CommonJS module is defined
    if (typeof module !== 'undefined' && module.exports) {
        module.exports = factory(require('jquery'));
    }
        // AMD module is defined
    else if (typeof define === 'function' && define.amd) {
        define(['jquery'], function ($) {
            return factory($);
        });
    } else {
        factory(root.jQuery);
    }

}(this, function ($) {

    'use strict';
    // jshint laxcomma: true


    /* TYPEAHEAD PUBLIC CLASS DEFINITION
     * ================================= */

    var Typeahead = function (element, options) {
        this.$element = $(element);
        this.options = $.extend({}, Typeahead.defaults, options);
        this.matcher = this.options.matcher || this.matcher;
        this.sorter = this.options.sorter || this.sorter;
        this.select = this.options.select || this.select;
        this.autoSelect = typeof this.options.autoSelect == 'boolean' ? this.options.autoSelect : true;
        this.highlighter = this.options.highlighter || this.highlighter;
        this.render = this.options.render || this.render;
        this.updater = this.options.updater || this.updater;
        this.displayText = this.options.displayText || this.displayText;
        this.source = this.options.source;
        this.delay = this.options.delay;
        this.$menu = $(this.options.menu);
        this.$appendTo = this.options.appendTo ? $(this.options.appendTo) : null;
        this.fitToElement = typeof this.options.fitToElement == 'boolean' ? this.options.fitToElement : false;
        this.shown = false;
        this.listen();
        this.showHintOnFocus = typeof this.options.showHintOnFocus == 'boolean' || this.options.showHintOnFocus === "all" ? this.options.showHintOnFocus : false;
        this.afterSelect = this.options.afterSelect;
        this.addItem = false;
        this.value = this.$element.val() || this.$element.text();
        this.keyPressed = false;
    };

    Typeahead.prototype = {

        constructor: Typeahead,

        select: function () {
            var val = this.$menu.find('.active').data('value');
            this.$element.data('active', val);
            if (this.autoSelect || val) {
                var newVal = this.updater(val);
                // Updater can be set to any random functions via "options" parameter in constructor above.
                // Add null check for cases when updater returns void or undefined.
                if (!newVal) {
                    newVal = '';
                }
                this.$element
                  .val(this.displayText(newVal) || newVal)
                  .text(this.displayText(newVal) || newVal)
                  .change();
                this.afterSelect(newVal);
            }
            return this.hide();
        },

        updater: function (item) {
            return item;
        },

        setSource: function (source) {
            this.source = source;
        },

        show: function () {
            var pos = $.extend({}, this.$element.position(), {
                height: this.$element[0].offsetHeight
            });

            var scrollHeight = typeof this.options.scrollHeight == 'function' ?
                this.options.scrollHeight.call() :
                this.options.scrollHeight;

            var element;
            if (this.shown) {
                element = this.$menu;
            } else if (this.$appendTo) {
                element = this.$menu.appendTo(this.$appendTo);
                this.hasSameParent = this.$appendTo.is(this.$element.parent());
            } else {
                element = this.$menu.insertAfter(this.$element);
                this.hasSameParent = true;
            }

            if (!this.hasSameParent) {
                // We cannot rely on the element position, need to position relative to the window
                element.css("position", "fixed");
                var offset = this.$element.offset();
                pos.top = offset.top;
                pos.left = offset.left;
            }
            // The rules for bootstrap are: 'dropup' in the parent and 'dropdown-menu-right' in the element.
            // Note that to get right alignment, you'll need to specify `menu` in the options to be:
            // '<ul class="typeahead dropdown-menu" role="listbox"></ul>'
            var dropup = $(element).parent().hasClass('dropup');
            var newTop = dropup ? 'auto' : (pos.top + pos.height + scrollHeight);
            var right = $(element).hasClass('dropdown-menu-right');
            var newLeft = right ? 'auto' : pos.left;
            // it seems like setting the css is a bad idea (just let Bootstrap do it), but I'll keep the old
            // logic in place except for the dropup/right-align cases.
            element.css({ top: newTop, left: newLeft }).show();

            if (this.options.fitToElement === true) {
                element.css("width", this.$element.outerWidth() + "px");
            }

            this.shown = true;
            return this;
        },

        hide: function () {
            this.$menu.hide();
            this.shown = false;
            return this;
        },

        lookup: function (query) {
            var items;
            if (typeof (query) != 'undefined' && query !== null) {
                this.query = query;
            } else {
                this.query = this.$element.val() || this.$element.text() || '';
            }

            if (this.query.length < this.options.minLength && !this.options.showHintOnFocus) {
                return this.shown ? this.hide() : this;
            }

            var worker = $.proxy(function () {

                // Bloodhound (since 0.11) needs three arguments. 
                // Two of them are callback functions (sync and async) for local and remote data processing
                // see https://github.com/twitter/typeahead.js/blob/master/src/bloodhound/bloodhound.js#L132
                if ($.isFunction(this.source) && this.source.length === 3) {
                    this.source(this.query, $.proxy(this.process, this), $.proxy(this.process, this));
                } else if ($.isFunction(this.source)) {
                    this.source(this.query, $.proxy(this.process, this));
                } else if (this.source) {
                    this.process(this.source);
                }
            }, this);

            clearTimeout(this.lookupWorker);
            this.lookupWorker = setTimeout(worker, this.delay);
        },

        process: function (items) {
            var that = this;

            items = $.grep(items, function (item) {
                return that.matcher(item);
            });

            items = this.sorter(items);

            if (!items.length && !this.options.addItem) {
                return this.shown ? this.hide() : this;
            }

            if (items.length > 0) {
                this.$element.data('active', items[0]);
            } else {
                this.$element.data('active', null);
            }

            if (this.options.items != 'all') {
                items = items.slice(0, this.options.items);
            }

            // Add item
            if (this.options.addItem) {
                items.push(this.options.addItem);
            }

            return this.render(items).show();
        },

        matcher: function (item) {
            var it = this.displayText(item);
            return ~it.toLowerCase().indexOf(this.query.toLowerCase());
        },

        sorter: function (items) {
            var beginswith = [];
            var caseSensitive = [];
            var caseInsensitive = [];
            var item;

            while ((item = items.shift())) {
                var it = this.displayText(item);
                if (!it.toLowerCase().indexOf(this.query.toLowerCase())) beginswith.push(item);
                else if (~it.indexOf(this.query)) caseSensitive.push(item);
                else caseInsensitive.push(item);
            }

            return beginswith.concat(caseSensitive, caseInsensitive);
        },

        highlighter: function (item) {
            var text = this.query;
            if (text === "") {
                return item;
            }
            var matches = item.match(/(>)([^<]*)(<)/g);
            var first = [];
            var second = [];
            var i;
            if (matches && matches.length) {
                //html
                for (i = 0; i < matches.length; ++i) {
                    if (matches[i].length > 2) {//escape '><'
                        first.push(matches[i]);
                    }
                }
            } else {
                //text
                first = [];
                first.push(item);
            }
            text = text.replace((/[\(\)\/\.\*\+\?\[\]]/g), function (mat) {
                return '\\' + mat;
            });
            var reg = new RegExp(text, "g");
            var m;
            for (i = 0; i < first.length; ++i) {
                m = first[i].match(reg);
                if (m && m.length > 0) {//find all text nodes matches
                    second.push(first[i]);
                }
            }
            for (i = 0; i < second.length; ++i) {
                item = item.replace(second[i], second[i].replace(reg, '<strong>$&</strong>'));
            }
            return item;
        },

        render: function (items) {
            var that = this;
            var self = this;
            var activeFound = false;
            var data = [];
            var _category = that.options.separator;

            $.each(items, function (key, value) {
                // inject separator
                if (key > 0 && value[_category] !== items[key - 1][_category]) {
                    data.push({
                        __type: 'divider'
                    });
                }

                // inject category header
                if (value[_category] && (key === 0 || value[_category] !== items[key - 1][_category])) {
                    data.push({
                        __type: 'category',
                        name: value[_category]
                    });
                }
                data.push(value);
            });

            items = $(data).map(function (i, item) {
                if ((item.__type || false) == 'category') {
                    return $(that.options.headerHtml).text(item.name)[0];
                }

                if ((item.__type || false) == 'divider') {
                    return $(that.options.headerDivider)[0];
                }

                var text = self.displayText(item);
                i = $(that.options.item).data('value', item);
                i.find('a').html(that.highlighter(text, item));
                if (text == self.$element.val()) {
                    i.addClass('active');
                    self.$element.data('active', item);
                    activeFound = true;
                }
                return i[0];
            });

            if (this.autoSelect && !activeFound) {
                items.filter(':not(.dropdown-header)').first().addClass('active');
                this.$element.data('active', items.first().data('value'));
            }
            this.$menu.html(items);
            return this;
        },

        displayText: function (item) {
            return typeof item !== 'undefined' && typeof item.name != 'undefined' ? item.name : item;
        },

        next: function (event) {
            var active = this.$menu.find('.active').removeClass('active');
            var next = active.next();

            if (!next.length) {
                next = $(this.$menu.find('li')[0]);
            }

            next.addClass('active');
            // added for screen reader
            this.$element.val(next.text());
        },

        prev: function (event) {
            var active = this.$menu.find('.active').removeClass('active');
            var prev = active.prev();

            if (!prev.length) {
                prev = this.$menu.find('li').last();
            }

            prev.addClass('active');
            // added for screen reader
            this.$element.val(prev.text());
        },

        listen: function () {
            this.$element
              .on('focus', $.proxy(this.focus, this))
              .on('blur', $.proxy(this.blur, this))
              .on('keypress', $.proxy(this.keypress, this))
              .on('propertychange input', $.proxy(this.input, this))
              .on('keyup', $.proxy(this.keyup, this));

            if (this.eventSupported('keydown')) {
                this.$element.on('keydown', $.proxy(this.keydown, this));
            }

            this.$menu
              .on('click', $.proxy(this.click, this))
              .on('mouseenter', 'li', $.proxy(this.mouseenter, this))
              .on('mouseleave', 'li', $.proxy(this.mouseleave, this))
              .on('mousedown', $.proxy(this.mousedown, this));
        },

        destroy: function () {
            this.$element.data('typeahead', null);
            this.$element.data('active', null);
            this.$element
              .off('focus')
              .off('blur')
              .off('keypress')
              .off('propertychange input')
              .off('keyup');

            if (this.eventSupported('keydown')) {
                this.$element.off('keydown');
            }

            this.$menu.remove();
            this.destroyed = true;
        },

        eventSupported: function (eventName) {
            var isSupported = eventName in this.$element;
            if (!isSupported) {
                this.$element.setAttribute(eventName, 'return;');
                isSupported = typeof this.$element[eventName] === 'function';
            }
            return isSupported;
        },

        move: function (e) {
            if (!this.shown) return;

            switch (e.keyCode) {
                case 9: // tab
                case 13: // enter
                case 27: // escape
                    e.preventDefault();
                    break;

                case 38: // up arrow
                    // with the shiftKey (this is actually the left parenthesis)
                    if (e.shiftKey) return;
                    e.preventDefault();
                    this.prev();
                    break;

                case 40: // down arrow
                    // with the shiftKey (this is actually the right parenthesis)
                    if (e.shiftKey) return;
                    e.preventDefault();
                    this.next();
                    break;
            }
        },

        keydown: function (e) {
            this.keyPressed = true;
            this.suppressKeyPressRepeat = ~$.inArray(e.keyCode, [40, 38, 9, 13, 27]);
            if (!this.shown && e.keyCode == 40) {
                this.lookup();
            } else {
                this.move(e);
            }
        },

        keypress: function (e) {
            if (this.suppressKeyPressRepeat) return;
            this.move(e);
        },

        input: function (e) {
            // This is a fixed for IE10/11 that fires the input event when a placehoder is changed
            // (https://connect.microsoft.com/IE/feedback/details/810538/ie-11-fires-input-event-on-focus)
            var currentValue = this.$element.val() || this.$element.text();
            if (this.value !== currentValue) {
                this.value = currentValue;
                this.lookup();
            }
        },

        keyup: function (e) {
            if (this.destroyed) {
                return;
            }
            switch (e.keyCode) {
                case 40: // down arrow
                case 38: // up arrow
                case 16: // shift
                case 17: // ctrl
                case 18: // alt
                    break;

                case 9: // tab
                    if (!this.shown || (this.showHintOnFocus && !this.keyPressed)) return;
                    this.select();
                    break;
                case 13: // enter
                    if (!this.shown) return;
                    this.select();
                    break;

                case 27: // escape
                    if (!this.shown) return;
                    this.hide();
                    break;
            }

        },

        focus: function (e) {
            if (!this.focused) {
                this.focused = true;
                this.keyPressed = false;
                if (this.options.showHintOnFocus && this.skipShowHintOnFocus !== true) {
                    if (this.options.showHintOnFocus === "all") {
                        this.lookup("");
                    } else {
                        this.lookup();
                    }
                }
            }
            if (this.skipShowHintOnFocus) {
                this.skipShowHintOnFocus = false;
            }
        },

        blur: function (e) {
            if (!this.mousedover && !this.mouseddown && this.shown) {
                this.hide();
                this.focused = false;
                this.keyPressed = false;
            } else if (this.mouseddown) {
                // This is for IE that blurs the input when user clicks on scroll.
                // We set the focus back on the input and prevent the lookup to occur again
                this.skipShowHintOnFocus = true;
                this.$element.focus();
                this.mouseddown = false;
            }
        },

        click: function (e) {
            e.preventDefault();
            this.skipShowHintOnFocus = true;
            this.select();
            this.$element.focus();
            this.hide();
        },

        mouseenter: function (e) {
            this.mousedover = true;
            this.$menu.find('.active').removeClass('active');
            $(e.currentTarget).addClass('active');
        },

        mouseleave: function (e) {
            this.mousedover = false;
            if (!this.focused && this.shown) this.hide();
        },

        /**
          * We track the mousedown for IE. When clicking on the menu scrollbar, IE makes the input blur thus hiding the menu.
          */
        mousedown: function (e) {
            this.mouseddown = true;
            this.$menu.one("mouseup", function (e) {
                // IE won't fire this, but FF and Chrome will so we reset our flag for them here
                this.mouseddown = false;
            }.bind(this));
        }

    };


    /* TYPEAHEAD PLUGIN DEFINITION
     * =========================== */

    var old = $.fn.typeahead;

    $.fn.typeahead = function (option) {
        var arg = arguments;
        if (typeof option == 'string' && option == 'getActive') {
            return this.data('active');
        }
        return this.each(function () {
            var $this = $(this);
            var data = $this.data('typeahead');
            var options = typeof option == 'object' && option;
            if (!data) $this.data('typeahead', (data = new Typeahead(this, options)));
            if (typeof option == 'string' && data[option]) {
                if (arg.length > 1) {
                    data[option].apply(data, Array.prototype.slice.call(arg, 1));
                } else {
                    data[option]();
                }
            }
        });
    };

    Typeahead.defaults = {
        source: [],
        items: 8,
        menu: '<ul class="typeahead dropdown-menu" role="listbox"></ul>',
        item: '<li><a class="dropdown-item" href="#" role="option"></a></li>',
        minLength: 1,
        scrollHeight: 0,
        autoSelect: true,
        afterSelect: $.noop,
        addItem: false,
        delay: 0,
        separator: 'category',
        headerHtml: '<li class="dropdown-header"></li>',
        headerDivider: '<li class="divider" role="separator"></li>'
    };

    $.fn.typeahead.Constructor = Typeahead;

    /* TYPEAHEAD NO CONFLICT
     * =================== */

    $.fn.typeahead.noConflict = function () {
        $.fn.typeahead = old;
        return this;
    };


    /* TYPEAHEAD DATA-API
     * ================== */

    $(document).on('focus.typeahead.data-api', '[data-provide="typeahead"]', function (e) {
        var $this = $(this);
        if ($this.data('typeahead')) return;
        $this.typeahead($this.data());
    });

}));;
/* Riot v3.0.0-rc, @license MIT */
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.riot=t()}(this,function(){"use strict";function e(e){return st.test(e)}function t(e){return ct.test(e)}function r(e){return typeof e===et||!1}function n(e){return e&&typeof e===Xe}function i(e){return typeof e===Ye}function o(e){return typeof e===Je}function a(e){return i(e)||null===e||""===e}function s(e){return Array.isArray(e)||e instanceof Array}function u(e,t){var r=Object.getOwnPropertyDescriptor(e,t);return i(e[t])||r&&r.writable}function c(e){return at.test(e)}function l(e,t){return(t||document).querySelectorAll(e)}function p(e,t){return(t||document).querySelector(e)}function f(){return document.createDocumentFragment()}function h(){return document.createTextNode("")}function d(e,t){return t?document.createElementNS("http://www.w3.org/2000/svg","svg"):document.createElement(e)}function g(e){if(e.outerHTML)return e.outerHTML;var t=d("div");return t.appendChild(e.cloneNode(!0)),t.innerHTML}function m(e,t){if(i(e.innerHTML)){var r=(new DOMParser).parseFromString(t,"application/xml"),n=e.ownerDocument.importNode(r.documentElement,!0);e.appendChild(n)}else e.innerHTML=t}function v(e,t){e.removeAttribute(t)}function x(e,t){return e.getAttribute(t)}function y(e,t,r){var n=rt.exec(t);n&&n[1]?e.setAttributeNS(tt,n[1],r):e.setAttribute(t,r)}function b(e,t,r){e.insertBefore(t,r.parentNode&&r)}function w(e,t){if(e)for(var r;r=ut.exec(e);)t(r[1].toLowerCase(),r[2]||r[3]||r[4])}function C(e,t,r){if(e){var n,i=t(e,r);if(i===!1)return;for(e=e.firstChild;e;)n=e.nextSibling,C(e,t,i),e=n}}function O(e,t){for(var r,n=e?e.length:0,i=0;i<n;++i)r=e[i],t(r,i)===!1&&i--;return e}function _(e,t){return~e.indexOf(t)}function E(e){return e.replace(/-(\w)/g,function(e,t){return t.toUpperCase()})}function S(e,t){return e.slice(0,t.length)===t}function j(e,t,r,n){return Object.defineProperty(e,t,N({value:r,enumerable:!1,writable:!1,configurable:!0},n)),e}function N(e){for(var t,r=arguments,n=1;n<r.length;++n)if(t=r[n])for(var i in t)u(e,i)&&(e[i]=t[i]);return e}function T(e,t,r){var n=this._parent,i=this._item;if(!i)for(;n&&!i;)i=n._item,n=n._parent;u(r,"currentTarget")&&(r.currentTarget=e),u(r,"target")&&(r.target=r.srcElement),u(r,"which")&&(r.which=r.charCode||r.keyCode),r.item=i,t.call(this,r),r.preventUpdate||oe(this).update()}function L(e,t,r,n){var i,o=T.bind(n,r,t);return r.addEventListener?(r[e]=null,i=e.replace(Ct,""),r._riotEvents||(r._riotEvents={}),r._riotEvents[e]&&r.removeEventListener(i,r._riotEvents[e]),r._riotEvents[e]=o,void r.addEventListener(i,o,!1)):void(r[e]=o)}function R(e,t){var r,n=yt(e.value,t);if(e.tag&&e.tagName===n)return void e.tag.update();if(e.tag){var i=e.tag.opts.dataIs,o=e.tag._parent.tags;y(e.tag.root,We,n),le(o,i,e.tag)}e.impl=Ze[n],r={root:e.dom,parent:t,hasImpl:!0,tagName:n},e.tag=ie(e.impl,r,e.dom.innerHTML,t),e.tagName=n,e.tag.mount(),e.tag.update(),t.on("unmount",function(){var t=e.tag.opts.dataIs,r=e.tag.parent.tags,n=e.tag._parent.tags;le(r,t,e.tag),le(n,t,e.tag),e.tag.unmount()})}function A(e){var t,n=e.dom,o=e.attr,a=yt(e.expr,this),s="value"===o,u=e.root&&"VIRTUAL"===e.root.tagName,c=n&&(e.parent||n.parentNode);if(e.bool?a=!!a&&o:(i(a)||null===a)&&(a=""),e._riot_id){if(e.isMounted)e.update();else if(e.mount(),u){var l=document.createDocumentFragment();he.call(e,l),e.root.parentElement.replaceChild(l,e.root)}}else{if(t=e.value,e.value=a,e.update)return void e.update();if(t!==a){if(e.isRtag&&a)return R(e,this);if(!s||n.value!==a){if(!o)return a+="",void(c&&(e.parent=c,"TEXTAREA"===c.tagName?(c.value=a,lt||(n.nodeValue=a)):n.nodeValue=a));if(e.isAttrRemoved||(v(n,o),e.isAttrRemoved=!0),r(a))L(o,a,n,this);else if(/^(show|hide)$/.test(o))"hide"===o&&(a=!a),n.style.display=a?"":"none";else if(s)n.value=a;else if(S(o,Qe)&&o!==We)null!=a&&y(n,o.slice(Qe.length),a);else{if("selected"===o&&c&&/^(SELECT|OPTGROUP)$/.test(c.tagName)&&null!=a&&(c.value=n.value),e.bool&&(n[o]=a,!a))return;(0===a||a&&typeof a!==Xe)&&y(n,o,a)}}}}}function M(e){O(e,A.bind(this))}function I(e,t,r,n){var i=n?Object.create(n):{};return i[e.key]=t,e.pos&&(i[e.pos]=r),i}function k(e,t,r,n){for(var i,o=t.length,a=e.length;o>a;)i=t[--o],t.splice(o,1),i.unmount(),le(n.tags,r,i,!0)}function $(e){var t=this;O(Object.keys(this.tags),function(r){var n=t.tags[r];s(n)?O(n,function(t){ne.apply(t,[r,e])}):ne.apply(n,[r,e])})}function F(e,t,r){r?de.apply(this,[e,t]):b(e,this.root,t.root)}function P(e,t,r){r?he.apply(this,[e,t]):b(e,this.root,t.root)}function H(e,t){t?he.call(this,e):e.appendChild(this.root)}function B(e,t,r){v(e,"each");var n,i=typeof x(e,"no-reorder")!==Je||v(e,"no-reorder"),o=se(e),a=Ze[o]||{tmpl:g(e)},u=it.test(o),c=e.parentNode,l=h(),p=te(e),d=x(e,"if"),m=[],y=[],b=!0,w=!Ze[o],C="VIRTUAL"===e.tagName;return r=yt.loopKeys(r),r.isLoop=!0,d&&v(e,"if"),c.insertBefore(l,e),c.removeChild(e),r.update=function(){var g,v,x,E=yt(r.val,t);c=l.parentNode,g?(x=h(""),g.insertBefore(x,c),g.removeChild(c)):v=f(),s(E)?n=!1:(n=E||!1,E=n?Object.keys(E).map(function(e){return I(r,E[e],e)}):[]),d&&(E=E.filter(function(e,n){return r.key?!!yt(d,I(r,e,n,t)):!!yt(d,t)||!!yt(d,e)})),O(E,function(s,l){var f=i&&typeof s===Xe&&!n,h=y.indexOf(s),d=~h&&f?h:l,g=m[d];if(s=!n&&r.key?I(r,s,l):s,!f&&!g||f&&!~h){var x=l===m.length;g=new ee(a,{parent:t,isLoop:b,isAnonymous:w,root:u?c:e.cloneNode(),item:s},e.innerHTML),g.mount(),x?H.apply(g,[v||c,C]):P.apply(g,[c,m[l],C]),x||y.splice(l,0,s),m.splice(l,0,g),p&&ce(t.tags,o,g,!0),d=l}else g.update(s);d!==l&&f&&(_(E,y[l])&&F.apply(g,[c,m[l],C]),r.pos&&(g[r.pos]=l),m.splice(l,0,m.splice(d,1)[0]),y.splice(l,0,y.splice(d,1)[0]),!p&&g.tags&&$.call(g,l)),g._item=s,j(g,"_parent",t)}),k(E,m,o,t),y=E.slice(),v?c.insertBefore(v,l):(g.insertBefore(c,x),g.removeChild(x))},r.unmount=function(){O(m,function(e){e.unmount()})},r}function z(e,t,r){var n=this,i={parent:{children:t}};return C(e,function(t,i){var o,a,s,u=t.nodeType,c=i.parent;if(!r&&t===e)return{parent:c};if(3===u&&"STYLE"!==t.parentNode.tagName&&yt.hasExpr(t.nodeValue)&&c.children.push({dom:t,expr:t.nodeValue}),1!==u)return i;if(o=x(t,"each"))return c.children.push(B(t,n,o)),!1;if(o=x(t,"if"))return c.children.push(Object.create(Ot).init(t,n,o)),!1;if((a=x(t,We))&&yt.hasExpr(a))return c.children.push({isRtag:!0,expr:a,dom:t}),!1;if(s=te(t),s&&(t!==e||r)){var l={root:t,parent:n,hasImpl:!0};return c.children.push(ie(s,l,t.innerHTML,n)),!1}return D.apply(n,[t,t.attributes,function(e,t){t&&c.children.push(t)}]),{parent:c}},i),{tree:i,root:e}}function D(e,r,n){var i=this;O(r,function(r){var o,a=r.name,s=t(a);~["ref","data-ref"].indexOf(a)?o=Object.create(_t).init(e,a,r.value,i):yt.hasExpr(r.value)&&(o={dom:e,expr:r.value,attr:r.name,bool:s}),n(r,o)})}function U(e,t,r){var n="o"===r[0],i=n?"select>":"table>";if(e.innerHTML="<"+i+t.trim()+"</"+i,i=e.firstChild,n)i.selectedIndex=-1;else{var o=Tt[r];o&&1===i.childElementCount&&(i=p(o,i))}return i}function V(e,t){if(!Et.test(e))return e;var r={};return t=t&&t.replace(jt,function(e,t,n){return r[t]=r[t]||n,""}).trim(),e.replace(Nt,function(e,t,n){return r[t]||n||""}).replace(St,function(e,r){return t||r||""})}function q(t,r,n){var i=t&&t.match(/^\s*<([-\w]+)/),o=i&&i[1].toLowerCase(),a=d(Rt,n&&e(o));return t=V(t,r),Lt.test(o)?a=U(a,t,o):m(a,t),a.stub=!0,a}function G(e,t){var r=this,n=r.name,i=r.tmpl,o=r.css,a=r.attrs,s=r.onCreate;return Ze[n]||(Z(n,i,o,a,s),Ze[n].class=this.constructor),fe(e,n,t,this),this}function Z(e,t,n,i,o){return r(i)&&(o=i,/^[\w\-]+\s?=/.test(n)?(i=n,n=""):i=""),n&&(r(n)?o=n:vt.add(n)),e=e.toLowerCase(),Ze[e]={name:e,tmpl:t,attrs:i,fn:o},e}function K(e,t,r,n,i){r&&vt.add(r,e);var o=!!Ze[e];return Ze[e]={name:e,tmpl:t,attrs:n,fn:i},o&&Pt.hotReloader&&Pt.hotReloader(e),e}function Q(e,t,r){function i(e){if(e.tagName){var n=x(e,We);t&&n!==t&&(n=t,y(e,We,t));var o=fe(e,n||e.tagName.toLowerCase(),r);o&&a.push(o)}else e.length&&O(e,i)}var a=[];vt.inject(),n(t)&&(r=t,t=0);var s,u;if(o(e)?(e="*"===e?u=ge():e+ge(e.split(/, */)),s=e?l(e):[]):s=e,"*"===t){if(t=u||ge(),s.tagName)s=l(t,s);else{var c=[];O(s,function(e){return c.push(l(t,e))}),s=c}t=0}return i(s),a}function W(e,t,o){if(n(e))return void W("__unnamed_"+It++,e,!0);var a=o?Mt:At;if(!t){if(i(a[e]))throw new Error("Unregistered mixin: "+e);return a[e]}a[e]=r(t)?N(t.prototype,a[e]||{})&&t:N(a[e]||{},t)}function J(){return O(Ge,function(e){return e.update()})}function X(e){delete Ze[e]}function Y(e,t,r,n,i){if(!e||!r){var o=!r&&e?this:t||this;O(i,function(e){e.expr&&M.call(o,[e.expr]),n[E(e.name)]=e.expr?e.expr.value:e.value})}}function ee(e,t,n){var i,a=N({},t.opts),s=t.parent,u=t.isLoop,c=t.isAnonymous,l=ue(t.item),p=[],f=[],h=[],d=t.root,g=t.tagName||d.tagName.toLowerCase(),m="virtual"===g,x=[];wt(this),e.name&&d._tag&&d._tag.unmount(!0),this.isMounted=!1,d.isLoop=u,j(this,"_internal",{isAnonymous:c,instAttrs:p,innerHTML:n,virts:[],tail:null,head:null}),j(this,"_riot_id",++kt),N(this,{parent:s,root:d,opts:a},l),j(this,"tags",{}),j(this,"refs",{}),i=q(e.tmpl,n,u),j(this,"update",function(e){if(!r(this.shouldUpdate)||this.shouldUpdate(e))return e=ue(e),u&&c&&re.apply(this,[this.parent,x]),N(this,e),Y.apply(this,[u,s,c,a,p]),this.isMounted&&this.trigger("update",e),M.call(this,h),this.isMounted&&this.trigger("updated"),this}.bind(this)),j(this,"mixin",function(){var e=this;return O(arguments,function(t){var n,i,a=[];t=o(t)?W(t):t,n=r(t)?new t:t;var s=Object.getPrototypeOf(n);do a=a.concat(Object.getOwnPropertyNames(i||n));while(i=Object.getPrototypeOf(i||n));O(a,function(t){if("init"!==t){var i=Object.getOwnPropertyDescriptor(n,t)||Object.getOwnPropertyDescriptor(s,t),o=i&&(i.get||i.set);!e.hasOwnProperty(t)&&o?Object.defineProperty(e,t,i):e[t]=r(n[t])?n[t].bind(e):n[t]}}),n.init&&n.init.bind(e)()}),this}.bind(this)),j(this,"mount",function(){var t=this;d._tag=this,D.apply(s,[d,d.attributes,function(e,r){!c&&_t.isPrototypeOf(r)&&(r.tag=t),e.expr=r,p.push(e)}]),f=[],w(e.attrs,function(e,t){f.push({name:e,value:t})}),D.apply(this,[d,f,function(e,t){t?h.push(t):y(d,e.name,e.value)}]),this._parent&&c&&re.apply(this,[this._parent,x]),Y.apply(this,[u,s,c,a,p]);var r=W(Ke);if(r)for(var n in r)r.hasOwnProperty(n)&&t.mixin(r[n]);if(e.fn&&e.fn.call(this,a),this.trigger("before-mount"),z.apply(this,[i,h,!1]),this.update(l),u&&c)this.root=d=i.firstChild;else{for(;i.firstChild;)d.appendChild(i.firstChild);d.stub&&(d=s.root)}return j(this,"root",d),this.isMounted=!0,!this.parent||this.parent.isMounted?this.trigger("mount"):this.parent.one("mount",function(){t.trigger("mount")}),this}.bind(this)),j(this,"unmount",function(e){var t,r=this,n=this.root,i=n.parentNode,o=Ge.indexOf(this);if(this.trigger("before-unmount"),~o&&Ge.splice(o,1),i){if(s)t=oe(s),m?Object.keys(this.tags).forEach(function(e){le(t.tags,e,r.tags[e])}):le(t.tags,g,this);else for(;n.firstChild;)n.removeChild(n.firstChild);e?v(i,We):i.removeChild(n)}return this._internal.virts&&O(this._internal.virts,function(e){e.parentNode&&e.parentNode.removeChild(e)}),ae(h),O(p,function(e){return e.expr&&e.expr.unmount&&e.expr.unmount()}),this.trigger("unmount"),this.off("*"),this.isMounted=!1,delete this.root._tag,this}.bind(this))}function te(e){return e.tagName&&Ze[x(e,We)||x(e,We)||e.tagName.toLowerCase()]}function re(e,t){var r=this;O(Object.keys(e),function(n){var o=!c(n)&&_(t,n);(i(r[n])||o)&&(o||t.push(n),r[n]=e[n])})}function ne(e,t){var r,n=this.parent;n&&(r=n.tags[e],s(r)?r.splice(t,0,r.splice(r.indexOf(this),1)[0]):ce(n.tags,e,this))}function ie(e,t,r,n){var i=new ee(e,t,r),o=t.tagName||se(t.root,!0),a=oe(n);return i.parent=a,i._parent=n,ce(a.tags,o,i),a!==n&&ce(n.tags,o,i),t.root.innerHTML="",i}function oe(e){for(var t=e;t._internal.isAnonymous&&t.parent;)t=t.parent;return t}function ae(e){O(e,function(e){e instanceof ee?e.unmount(!0):e.unmount&&e.unmount()})}function se(e,t){var r=te(e),n=!t&&x(e,"name"),i=n&&!yt.hasExpr(n)?n:r?r.name:e.tagName.toLowerCase();return i}function ue(e){if(!(e instanceof ee||e&&typeof e.trigger===et))return e;var t={};for(var r in e)at.test(r)||(t[r]=e[r]);return t}function ce(e,t,r,n){var i=e[t],o=s(i);i&&i===r||(!i&&n?e[t]=[r]:i?(!o||o&&!_(i,r))&&(o?i.push(r):e[t]=[i,r]):e[t]=r)}function le(e,t,r,n){s(e[t])?(O(e[t],function(n,i){n===r&&e[t].splice(i,1)}),e[t].length?1!==e[t].length||n||(e[t]=e[t][0]):delete e[t]):delete e[t]}function pe(e){for(;e;){if(e.inStub)return!0;e=e.parentNode}return!1}function fe(e,t,r,n){var i=Ze[t],o=Ze[t].class,a=n||(o?Object.create(o.prototype):{}),s=e._innerHTML=e._innerHTML||e.innerHTML;e.innerHTML="";var u={root:e,opts:r};return r&&r.parent&&(u.parent=r.parent),i&&e&&ee.apply(a,[i,u,s]),a&&a.mount&&(a.mount(!0),_(Ge,a)||Ge.push(a)),a}function he(e,t){var r,n,i=this,o=h(),a=h(),s=f();for(this._internal.head=this.root.insertBefore(o,this.root.firstChild),this._internal.tail=this.root.appendChild(a),n=this._internal.head;n;)r=n.nextSibling,s.appendChild(n),i._internal.virts.push(n),n=r;t?e.insertBefore(s,t._internal.head):e.appendChild(s)}function de(e,t){for(var r,n=this,i=this._internal.head,o=f();i;)if(r=i.nextSibling,o.appendChild(i),i=r,i===n._internal.tail){o.appendChild(i),e.insertBefore(o,t._internal.head);break}}function ge(e){if(!e){var t=Object.keys(Ze);return t+ge(t)}return e.filter(function(e){return!/[^-\w]/.test(e)}).reduce(function(e,t){var r=t.trim().toLowerCase();return e+",["+We+'="'+r+'"]'},"")}function me(e){var t=arguments,r=e.source,n=e.global?"g":"";e.ignoreCase&&(n+="i"),e.multiline&&(n+="m");for(var i=1;i<arguments.length;i++)r=r.replace("@","\\"+t[i]);return new RegExp(r,n)}function ve(e){var t,r=qt;for(~e.indexOf("\r")&&(e=e.replace(/\r\n?/g,"\n")),r.lastIndex=0;t=r.exec(e);)"<"===t[0][0]&&(e=RegExp.leftContext+RegExp.rightContext,r.lastIndex=t[3]+1);return e}function xe(e,t){var r,n,i,o=[];for(Vt.lastIndex=0,e=e.replace(/\s+/g," ");r=Vt.exec(e);){var a=r[1].toLowerCase(),s=r[2];s?(s[0]!==ir&&(s=ir+(s[0]===or?s.slice(1,-1):s)+ir),"type"===a&&Jt.test(s)?n=s:(er.test(s)&&("value"===a&&(i=1),~Kt.indexOf(a)&&(a="riot-"+a)),o.push(a+"="+s))):o.push(a)}return n&&(i&&(n=ir+t._bp[0]+or+n.slice(1,-1)+or+t._bp[1]+ir),o.push("type="+n)),o.join(" ")}function ye(e,t,r){var n=r._bp;if(e&&n[4].test(e)){for(var i,o=t.expr&&(t.parser||t.type)?_e:0,a=xt.split(e,0,n),s=1;s<a.length;s+=2)i=a[s],"^"===i[0]?i=i.slice(1):o&&(i=o(i,t).trim(),";"===i.slice(-1)&&(i=i.slice(0,-1))),a[s]=rr+(r.push(i)-1)+n[1];e=a.join("")}return e}function be(e,t){return t.length&&(e=e.replace(tr,function(e,r){return t._bp[0]+t[r].trim().replace(/[\r\n]+/g," ").replace(/"/g,nr)})),e}function we(e,t,r){if(!/\S/.test(e))return"";if(e=ye(e,t,r).replace(Gt,function(e,t,n,i){return t=t.toLowerCase(),i=i&&!Qt.test(t)?"></"+t:"",n&&(t+=" "+xe(n,r)),"<"+t+i+">"}),!t.whitespace){var n=[];/<pre[\s>]/.test(e)&&(e=e.replace(Wt,function(e){return n.push(e),""})),e=e.trim().replace(/\s+/g," "),n.length&&(e=e.replace(/\u0002/g,function(){return n.shift()}))}return t.compact&&(e=e.replace(Zt,"><$1")),be(e,r).replace(Yt,"")}function Ce(e,t,r){return Array.isArray(t)?(r=t,t={}):(r||(r=[]),t||(t={})),r._bp=xt.array(t.brackets),we(ve(e),t,r)}function Oe(e){function t(e,t,r){for(t.lastIndex=0;r=t.exec(e);)"/"!==r[0][0]||r[1]||r[2]||(e=u.leftContext+" "+u.rightContext,t.lastIndex=r[3]+1);return e}function r(e,t){var r,n=1;for(t.lastIndex=0;n&&(r=t.exec(e));)"{"===r[0]?++n:"}"===r[0]&&--n;return n?e.length:t.lastIndex}var n,i,o,a,s=[],u=RegExp;for(~e.indexOf("/")&&(e=t(e,ur));n=e.match(ar);)s.push(u.leftContext),e=u.rightContext,o=r(e,sr),a=n[1],i=!/^(?:if|while|for|switch|catch|function)$/.test(a),a=i?n[0].replace(a,"this."+a+" = function"):n[0],s.push(a,e.slice(0,o)),e=e.slice(o),i&&!/^\s*.\s*bind\b/.test(e)&&s.push(".bind(this)");return s.length?s.join("")+e:e}function _e(e,t,r,n,i){if(!/\S/.test(e))return"";r||(r=t.type);var o=t.parser||r&&Bt._req("js."+r,!0)||Oe;return o(e,n,i).replace(/\r\n?/g,"\n").replace(Yt,"")}function Ee(e,t,r,n){return"string"==typeof t&&(n=r,r=t,t={}),r&&"object"==typeof r&&(n=r,r=""),n||(n={}),_e(e,t||{},r,n.parserOptions,n.url)}function Se(e,t){var r=":scope";return t.replace(cr,function(t,n,i){return i?(i=i.replace(/[^,]+/g,function(t){var n=t.trim();return 0===n.indexOf(e)?t:n&&"from"!==n&&"to"!==n&&"%"!==n.slice(-1)?n=n.indexOf(r)<0?e+" "+n+',[data-is="'+e+'"] '+n:n.replace(r,e)+","+n.replace(r,'[data-is="'+e+'"]'):t}),n?n+" "+i:i):t})}function je(e,t,r,n){if(n=n||{},r&&"css"!==r){var i=Bt._req("css."+r,!0);e=i(t,e,n.parserOpts||{},n.url)}return e=e.replace(xt.R_MLCOMMS,"").replace(/\s+/g," ").trim(),t&&(e=Se(t,e)),e}function Ne(e,t,r){return t&&"object"==typeof t?(r=t,t=""):r||(r={}),je(e,r.tagName,t,r)}function Te(e,t){return e?(e=or+e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")+or,t&&~e.indexOf("\n")?e.replace(/\n/g,"\\n"):e):"''"}function Le(e,t,r,n,i,o,a){var s=a.debug?",\n  ":", ",u="});";return i&&"\n"!==i.slice(-1)&&(u="\n"+u),o+"riot.tag2('"+e+or+s+Te(t,1)+s+Te(r)+s+Te(n)+", function(opts) {\n"+i+u}function Re(e){if(/<[-\w]/.test(e))for(var t,r=e.lastIndexOf("<"),n=e.length;~r;){if(t=e.slice(r,n).match(fr))return r+=t.index+t[0].length,t=e.slice(0,r),"<-/>\n"===t.slice(-5)&&(t=t.slice(0,-5)),[t,e.slice(r)];n=r,r=e.lastIndexOf("<",r-1)}return["",e]}function Ae(e){if(e){var t=e.match(lr);if(t=t&&(t[2]||t[3]))return t.replace("text/","")}return""}function Me(e,t){if(e){var r=e.match(RegExp("\\s"+t+pr,"i"));if(r=r&&r[1])return/^['"]/.test(r)?r.slice(1,-1):r}return""}function Ie(e){return e.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#039;/g,"'")}function ke(e){var t=Ie(Me(e,"options"));return t?JSON.parse(t):null}function $e(e,t,r,n){var i=Ae(r),o=Me(r,"src"),a=zt({},t.parserOptions.js);return!o&&_e(e,t,i,zt(a,ke(r)),n)}function Fe(e,t,r,n,i){var o=zt({},t.parserOptions.style),a={parserOpts:zt(o,ke(r)),url:n};return je(e,i,Ae(r)||t.style,a)}function Pe(e,t,r,n){var i=Bt._req("html."+r,!0);return i(e,n,t)}function He(e,t,r){var n,i=[],o={template:{},js:{},style:{}};t||(t={}),t.parserOptions=zt(o,t.parserOptions||{}),n=t.exclude?function(e){return t.exclude.indexOf(e)<0}:function(){return 1},r||(r="");var a=xt.array(t.brackets);return t.template&&(e=Pe(e,r,t.template,t.parserOptions.template)),e=ve(e).replace(hr,function(e,o,s,u,c,l){var p="",f="",h="",d="",g=[];if(g._bp=a,s=s.toLowerCase(),u=u&&n("attribs")?be(xe(ye(u,t,g),g),g):"",(c||(c=l))&&/\S/.test(c))if(l)n("html")&&(h=we(l,t,g));else{c=c.replace(RegExp("^"+o,"gm"),""),c=c.replace(gr,function(e,i,o){return n("css")&&(f+=(f?" ":"")+Fe(o,t,i,r,s)),""}),c=c.replace(dr,function(e,i,o){if(n("js")){var a=$e(o,t,i,r);a&&(p+=(p?"\n":"")+a)}return""});var m=Re(c.replace(Yt,""));n("html")&&(h=we(m[0],t,g)),n("js")&&(c=_e(m[1],t,null,null,r),c&&(p+=(p?"\n":"")+c),p=p.replace(Xt,function(e){return d+=e.trim()+"\n",""}))}return p=/\S/.test(p)?p.replace(/\n{3,}/g,"\n\n"):"",t.entities?(i.push({tagName:s,html:h,css:f,attribs:u,js:p,imports:d}),""):Le(s,h,f,u,p,d,t)}),t.entities?i:e}function Be(e,t,r){var n=new XMLHttpRequest;n.onreadystatechange=function(){4===n.readyState&&(200===n.status||!n.status&&n.responseText.length)&&t(n.responseText,r,e)},n.open("GET",e,!0),n.send("")}function ze(e,t){if(typeof e===Je){var r=d("script"),n=document.documentElement;t&&(e+="\n//# sourceURL="+t+".js"),r.text=e,n.appendChild(r),n.removeChild(r)}}function De(e,t){function r(){gt.trigger("ready"),mt=!0,e&&e()}function n(e,t,n){var i=vr.compile(e,t,n);ze(i,n),--o||r()}var i=l('script[type="riot/tag"]'),o=i.length;if(o)for(var a=0;a<i.length;++a){var s=i[a],u=N({template:x(s,"template")},t),c=x(s,"src");c?Be(c,n,u):n(s.innerHTML,u)}else r()}function Ue(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];var r;return yr(function(){r=Q.apply(Ht,e)}),r}var Ve,qe,Ge=[],Ze={},Ke="__global_mixin",Qe="riot-",We="data-is",Je="string",Xe="object",Ye="undefined",et="function",tt="http://www.w3.org/1999/xlink",rt=/^xlink:(\w+)/,nt=typeof window===Ye?void 0:window,it=/^(?:t(?:body|head|foot|[rhd])|caption|col(?:group)?|opt(?:ion|group))$/,ot=/^(?:t(?:body|head|foot|[rhd])|caption|col(?:group)?)$/,at=/^(?:_(?:item|id|parent)|update|root|(?:un)?mount|mixin|is(?:Mounted|Loop)|tags|parent|opts|trigger|o(?:n|ff|ne))$/,st=/^(altGlyph|animate(?:Color)?|circle|clipPath|defs|ellipse|fe(?:Blend|ColorMatrix|ComponentTransfer|Composite|ConvolveMatrix|DiffuseLighting|DisplacementMap|Flood|GaussianBlur|Image|Merge|Morphology|Offset|SpecularLighting|Tile|Turbulence)|filter|font|foreignObject|g(?:lyph)?(?:Ref)?|image|line(?:arGradient)?|ma(?:rker|sk)|missing-glyph|path|pattern|poly(?:gon|line)|radialGradient|rect|stop|svg|switch|symbol|text(?:Path)?|tref|tspan|use)$/,ut=/([-\w]+) ?= ?(?:"([^"]*)|'([^']*)|({[^}]*}))/g,ct=/^(?:disabled|checked|readonly|required|allowfullscreen|auto(?:focus|play)|compact|controls|default|formnovalidate|hidden|ismap|itemscope|loop|multiple|muted|no(?:resize|shade|validate|wrap)?|open|reversed|seamless|selected|sortable|truespeed|typemustmatch)$/,lt=0|(nt&&nt.document||{}).documentMode,pt=Object.freeze({isSVGTag:e,isBoolAttr:t,isFunction:r,isObject:n,isUndefined:i,isString:o,isBlank:a,isArray:s,isWritable:u,isReservedName:c}),ft=Object.freeze({$$:l,$:p,createFrag:f,createDOMPlaceholder:h,mkEl:d,getOuterHTML:g,setInnerHTML:m,remAttr:v,getAttr:x,setAttr:y,safeInsert:b,walkAttrs:w,walkNodes:C}),ht={},dt=[];nt&&(Ve=function(){var e=d("style");y(e,"type","text/css");var t=p("style[type=riot]");return t?(t.id&&(e.id=t.id),t.parentNode.replaceChild(e,t)):document.getElementsByTagName("head")[0].appendChild(e),e}(),qe=Ve.styleSheet);var gt,mt,vt={styleNode:Ve,add:function(e,t){t?ht[t]=e:dt.push(e)},inject:function(){if(nt){var e=Object.keys(ht).map(function(e){return ht[e]}).concat(dt).join("\n");qe?qe.cssText=e:Ve.innerHTML=e}}},xt=function(e){function t(e){return e}function r(e,t){return t||(t=y),new RegExp(e.source.replace(/{/g,t[2]).replace(/}/g,t[3]),e.global?c:"")}function n(e){if(e===m)return v;var t=e.split(" ");if(2!==t.length||h.test(e))throw new Error('Unsupported brackets "'+e+'"');return t=t.concat(e.replace(d,"\\").split(" ")),t[4]=r(t[1].length>1?/{[\S\s]*?}/:v[4],t),t[5]=r(e.length>3?/\\({|})/g:v[5],t),t[6]=r(v[6],t),t[7]=RegExp("\\\\("+t[3]+")|([[({])|("+t[3]+")|"+f,c),t[8]=e,t}function i(e){return e instanceof RegExp?s(e):y[e]}function o(e){(e||(e=m))!==y[8]&&(y=n(e),s=e===m?t:r,y[9]=s(v[9])),x=e}function a(e){var t;e=e||{},t=e.brackets,Object.defineProperty(e,"brackets",{set:o,get:function(){return x},enumerable:!0}),u=e,o(t)}var s,u,c="g",l=/\/\*[^*]*\*+(?:[^*\/][^*]*\*+)*\//g,p=/"[^"\\]*(?:\\[\S\s][^"\\]*)*"|'[^'\\]*(?:\\[\S\s][^'\\]*)*'/g,f=p.source+"|"+/(?:\breturn\s+|(?:[$\w\)\]]|\+\+|--)\s*(\/)(?![*\/]))/.source+"|"+/\/(?=[^*\/])[^[\/\\]*(?:(?:\[(?:\\.|[^\]\\]*)*\]|\\.)[^[\/\\]*)*?(\/)[gim]*/.source,h=RegExp("[\\x00-\\x1F<>a-zA-Z0-9'\",;\\\\]"),d=/(?=[[\]()*+?.^$|])/g,g={"(":RegExp("([()])|"+f,c),"[":RegExp("([[\\]])|"+f,c),"{":RegExp("([{}])|"+f,c)},m="{ }",v=["{","}","{","}",/{[^}]*}/,/\\([{}])/g,/\\({)|{/g,RegExp("\\\\(})|([[({])|(})|"+f,c),m,/^\s*{\^?\s*([$\w]+)(?:\s*,\s*(\S+))?\s+in\s+(\S.*)\s*}/,/(^|[^\\]){=[\S\s]*?}/],x=e,y=[];return i.split=function(e,t,r){function n(e){t||a?c.push(e&&e.replace(r[5],"$1")):c.push(e)}function i(e,t,r){var n,i=g[t];for(i.lastIndex=r,r=1;(n=i.exec(e))&&(!n[1]||(n[1]===t?++r:--r)););return r?e.length:i.lastIndex}r||(r=y);var o,a,s,u,c=[],l=r[6];for(a=s=l.lastIndex=0;o=l.exec(e);){if(u=o.index,a){if(o[2]){l.lastIndex=i(e,o[2],l.lastIndex);continue}if(!o[3])continue}o[1]||(n(e.slice(s,u)),s=l.lastIndex,l=r[6+(a^=1)],l.lastIndex=s)}return e&&s<e.length&&n(e.slice(s)),c},i.hasExpr=function(e){return y[4].test(e)},i.loopKeys=function(e){var t=e.match(y[9]);return t?{key:t[1],pos:t[2],val:y[0]+t[3].trim()+y[1]}:{val:e.trim()}},i.array=function(e){return e?n(e):y},Object.defineProperty(i,"settings",{set:a,get:function(){return u}}),i.settings="undefined"!=typeof riot&&riot.settings||{},i.set=o,i.R_STRINGS=p,i.R_MLCOMMS=l,i.S_QBLOCKS=f,i}(),yt=function(){function e(e,n){return e?(a[e]||(a[e]=r(e))).call(n,t):e}function t(t,r){e.errorHandler&&(t.riotData={tagName:r&&r.root&&r.root.tagName,_riot_id:r&&r._riot_id},e.errorHandler(t))}function r(e){var t=n(e);return"try{return "!==t.slice(0,11)&&(t="return "+t),new Function("E",t+";")}function n(e){var t,r=[],n=xt.split(e.replace(l,'"'),1);if(n.length>2||n[0]){var o,a,s=[];for(o=a=0;o<n.length;++o)t=n[o],t&&(t=1&o?i(t,1,r):'"'+t.replace(/\\/g,"\\\\").replace(/\r\n?|\n/g,"\\n").replace(/"/g,'\\"')+'"')&&(s[a++]=t);t=a<2?s[0]:"["+s.join(",")+'].join("")'}else t=i(n[1],0,r);return r[0]&&(t=t.replace(p,function(e,t){return r[t].replace(/\r/g,"\\r").replace(/\n/g,"\\n")})),t}function i(e,t,r){function n(t,r){var n,i=1,o=f[t];for(o.lastIndex=r.lastIndex;n=o.exec(e);)if(n[0]===t)++i;else if(!--i)break;r.lastIndex=i?e.length:o.lastIndex}if(e=e.replace(c,function(e,t){return e.length>2&&!t?s+(r.push(e)-1)+"~":e}).replace(/\s+/g," ").trim().replace(/\ ?([[\({},?\.:])\ ?/g,"$1")){for(var i,a=[],l=0;e&&(i=e.match(u))&&!i.index;){var p,h,d=/,|([[{(])|$/g;for(e=RegExp.rightContext,p=i[2]?r[i[2]].slice(1,-1).trim().replace(/\s+/g," "):i[1];h=(i=d.exec(e))[1];)n(h,d);h=e.slice(0,i.index),e=RegExp.rightContext,a[l++]=o(h,1,p)}e=l?l>1?"["+a.join(",")+'].join(" ").trim()':a[0]:o(e,t)}return e}function o(e,t,r){var n;return e=e.replace(d,function(e,t,r,i,o){return r&&(i=n?0:i+e.length,"this"!==r&&"global"!==r&&"window"!==r?(e=t+'("'+r+h+r,i&&(n="."===(o=o[i])||"("===o||"["===o)):i&&(n=!g.test(o.slice(i)))),e}),n&&(e="try{return "+e+"}catch(e){E(e,this)}"),r?e=(n?"function(){"+e+"}.call(this)":"("+e+")")+'?"'+r+'":""':t&&(e="function(v){"+(n?e.replace("return ","v="):"v=("+e+")")+';return v||v===0?v:""}.call(this)'),e}var a={};e.haveRaw=xt.hasRaw,e.hasExpr=xt.hasExpr,e.loopKeys=xt.loopKeys,e.clearCache=function(){a={}},e.errorHandler=null;var s=String.fromCharCode(8279),u=/^(?:(-?[_A-Za-z\xA0-\xFF][-\w\xA0-\xFF]*)|\u2057(\d+)~):/,c=RegExp(xt.S_QBLOCKS,"g"),l=/\u2057/g,p=/\u2057(\d+)~/g,f={"(":/[()]/g,"[":/[[\]]/g,"{":/[{}]/g},h='"in this?this:'+("object"!=typeof window?"global":"window")+").",d=/[,{][\$\w]+(?=:)|(^ *|[^$\w\.{])(?!(?:typeof|true|false|null|undefined|in|instanceof|is(?:Finite|NaN)|void|NaN|new|Date|RegExp|Math)(?![$\w]))([$_A-Za-z][$\w]*)/g,g=/^(?=(\.[$\w]+))\1(?:[^.[(]|$)/;return e.version=xt.version="v2.4.2",e}(),bt=Object.freeze({each:O,contains:_,toCamel:E,startsWith:S,defineProperty:j,extend:N}),wt=function(e){e=e||{};var t={},r=Array.prototype.slice;return Object.defineProperties(e,{on:{value:function(r,n){return"function"==typeof n&&(t[r]=t[r]||[]).push(n),e},enumerable:!1,writable:!1,configurable:!1},off:{value:function(r,n){if("*"!=r||n)if(n)for(var i,o=t[r],a=0;i=o&&o[a];++a)i==n&&o.splice(a--,1);else delete t[r];else t={};return e},enumerable:!1,writable:!1,configurable:!1},one:{value:function(t,r){function n(){e.off(t,n),r.apply(e,arguments)}return e.on(t,n)},enumerable:!1,writable:!1,configurable:!1},trigger:{value:function(n){var i,o,a,s=arguments,u=arguments.length-1,c=new Array(u);for(a=0;a<u;a++)c[a]=s[a+1];for(i=r.call(t[n]||[],0),a=0;o=i[a];++a)o.apply(e,c);return t["*"]&&"*"!=n&&e.trigger.apply(e,["*",n].concat(c)),e},enumerable:!1,writable:!1,configurable:!1}}),e},Ct=/^on/,Ot={init:function(e,t,r){v(e,"if"),this.parentTag=t,this.expr=r,this.stub=document.createTextNode(""),this.pristine=e;var n=e.parentNode;return n.insertBefore(this.stub,e),n.removeChild(e),this},update:function(){var e=yt(this.expr,this.parentTag);e&&!this.current?(this.current=this.pristine.cloneNode(!0),this.stub.parentNode.insertBefore(this.current,this.stub),this.expressions=[],z.apply(this.parentTag,[this.current,this.expressions,!0])):!e&&this.current&&(ae(this.expressions),this.current.parentNode.removeChild(this.current),this.current=null,this.expressions=[]),e&&M.call(this.parentTag,this.expressions)},unmount:function(){ae(this.expressions||[]),delete this.pristine,delete this.parentNode,delete this.stub}},_t={init:function(e,t,r,n){return this.dom=e,this.attr=t,this.rawValue=r,this.parent=n,this.hasExp=yt.hasExpr(r),this.firstRun=!0,this},update:function(){var e=this.rawValue;if(this.hasExp&&(e=yt(this.rawValue,this.parent)),this.firstRun||e!==this.value){var t=this.parent&&oe(this.parent),r=this.tag||this.dom;!a(this.value)&&t&&le(t.refs,this.value,r),a(e)?v(this.dom,this.attr):(t&&ce(t.refs,e,r),y(this.dom,this.attr,e)),this.value=e,this.firstRun=!1}},unmount:function(){var e=this.tag||this.dom,t=this.parent&&oe(this.parent);!a(this.value)&&t&&le(t.refs,this.value,e),delete this.dom,delete this.parent}},Et=/<yield\b/i,St=/<yield\s*(?:\/>|>([\S\s]*?)<\/yield\s*>|>)/gi,jt=/<yield\s+to=['"]([^'">]*)['"]\s*>([\S\s]*?)<\/yield\s*>/gi,Nt=/<yield\s+from=['"]?([-\w]+)['"]?\s*(?:\/>|>([\S\s]*?)<\/yield\s*>)/gi,Tt={tr:"tbody",th:"tr",td:"tr",col:"colgroup"},Lt=lt&&lt<10?it:ot,Rt="div",At={},Mt=At[Ke]={},It=0,kt=0,$t=Object.freeze({getTag:te,inheritFrom:re,moveChildTag:ne,initChildTag:ie,getImmediateCustomParentTag:oe,unmountAll:ae,getTagName:se,cleanUpData:ue,arrayishAdd:ce,arrayishRemove:le,isInStub:pe,mountTo:fe,makeVirtual:he,moveVirtual:de,selectTags:ge}),Ft=Object.create(xt.settings),Pt={tmpl:yt,brackets:xt,styleManager:vt,vdom:Ge,styleNode:vt.styleNode,dom:ft,check:pt,misc:bt,tags:$t},Ht=Object.freeze({settings:Ft,util:Pt,observable:wt,Tag:G,tag:Z,tag2:K,mount:Q,mixin:W,update:J,unregister:X}),Bt=function(e){function t(t){var r=e[t];if(r)return r;throw new Error('Parser "'+t+'" not loaded.')}function r(e){var t=e.split(".");if(2!==t.length)throw new Error("Bad format for parsers._req");var r=o[t[0]][t[1]];if(r)return r;throw new Error('Parser "'+e+'" not found.')}function n(e,t){if(t)for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r]);return e}function i(e,r,i,o){return i=n({pretty:!0,filename:o,doctype:"html"},i),t(e).render(r,i)}var o={};return o.html={jade:function(e,t,r){return console.log('DEPRECATION WARNING: jade was renamed "pug" - The jade parser will be removed in riot@3.0.0!'),i("jade",e,t,r)},pug:function(e,t,r){return i("pug",e,t,r)}},o.css={less:function(e,r,i,o){var a;return i=n({sync:!0,syncImport:!0,filename:o},i),t("less").render(r,i,function(e,t){if(e)throw e;a=t.css}),a}},o.js={es6:function(e,r){return r=n({blacklist:["useStrict","strict","react"],sourceMaps:!1,comments:!1},r),t("babel").transform(e,r).code},babel:function(e,r,i){return t("babel").transform(e,n({filename:i},r)).code},buble:function(e,r,i){return r=n({source:i,modules:!1},r),t("buble").transform(e,r).code},coffee:function(e,r){return t("CoffeeScript").compile(e,n({bare:!0},r))},livescript:function(e,r){return t("livescript").compile(e,n({bare:!0,header:!1},r))},typescript:function(e,r){return t("typescript")(e,r)},none:function(e){return e}},o.js.javascript=o.js.none,o.js.coffeescript=o.js.coffee,o._req=r,o.utils={extend:n},o}(window||global),zt=Bt.utils.extend,Dt=/"[^"\n\\]*(?:\\[\S\s][^"\n\\]*)*"|'[^'\n\\]*(?:\\[\S\s][^'\n\\]*)*'/.source,Ut=xt.R_STRINGS.source,Vt=/ *([-\w:\xA0-\xFF]+) ?(?:= ?('[^']*'|"[^"]*"|\S+))?/g,qt=RegExp(/<!--(?!>)[\S\s]*?-->/.source+"|"+Dt,"g"),Gt=/<(-?[A-Za-z][-\w\xA0-\xFF]*)(?:\s+([^"'\/>]*(?:(?:"[^"]*"|'[^']*'|\/[^>])[^'"\/>]*)*)|\s*)(\/?)>/g,Zt=/>[ \t]+<(-?[A-Za-z]|\/[-A-Za-z])/g,Kt=["style","src","d","value"],Qt=/^(?:input|img|br|wbr|hr|area|base|col|embed|keygen|link|meta|param|source|track)$/,Wt=/<pre(?:\s+(?:[^">]*|"[^"]*")*)?>([\S\s]+?)<\/pre\s*>/gi,Jt=/^"(?:number|date(?:time)?|time|month|email|color)\b/i,Xt=/^\s*import(?:(\s|\S)*)['|"]/gm,Yt=/[ \t]+$/gm,er=me(/@#\d/,"x01"),tr=me(/@#(\d+)/g,"x01"),rr="#",nr="⁗",ir='"',or="'",ar=/^[ \t]*([$_A-Za-z][$\w]*)\s*\([^()]*\)\s*{/m,sr=RegExp("[{}]|"+xt.S_QBLOCKS,"g"),ur=RegExp(xt.R_MLCOMMS.source+"|//[^\r\n]*|"+xt.S_QBLOCKS,"g"),cr=RegExp("([{}]|^)[ ;]*([^@ ;{}][^{}]*)(?={)|"+Dt,"g"),lr=/\stype\s*=\s*(?:(['"])(.+?)\1|(\S+))/i,pr="\\s*=\\s*("+Ut+"|{[^}]+}|\\S+)",fr=/\/>\n|^<(?:\/?-?[A-Za-z][-\w\xA0-\xFF]*\s*|-?[A-Za-z][-\w\xA0-\xFF]*\s+[-\w:\xA0-\xFF][\S\s]*?)>\n/,hr=RegExp(/^([ \t]*)<(-?[A-Za-z][-\w\xA0-\xFF]*)(?:\s+([^'"\/>]+(?:(?:@|\/[^>])[^'"\/>]*)*)|\s*)?(?:\/>|>[ \t]*\n?([\S\s]*)^\1<\/\2\s*>|>(.*)<\/\2\s*>)/.source.replace("@",Ut),"gim"),dr=/<script(\s+[^>]*)?>\n?([\S\s]*?)<\/script\s*>/gi,gr=/<style(\s+[^>]*)?>\n?([\S\s]*?)<\/style\s*>/gi,mr="v3.0.0-alpha.4",vr={
compile:He,compileHTML:Ce,compileCSS:Ne,compileJS:Ee,parsers:Bt,version:mr},xr=vr.parsers,yr=function(e,t,i){if(typeof e===Je){if(n(t)&&(i=t,t=!1),/^\s*</m.test(e)){var o=vr.compile(e,i);return t!==!0&&ze(o),r(t)&&t(o,e,i),o}Be(e,function(e,r,n){var i=vr.compile(e,r,n);ze(i,n),t&&t(i,e,r)},i)}else if(s(e)){var a=e.length;e.forEach(function(e){Be(e,function(e,r,n){var i=vr.compile(e,r,n);ze(i,n),a--,!a&&t&&t(i,e,r)},i)})}else{if(r(e)?(i=t,t=e):(i=e,t=void 0),mt)return t&&t();gt?t&&gt.on("ready",t):(gt=wt(),De(t,i))}},br=N({},Ht,{mount:Ue,compile:yr,parsers:xr});return br});;
!function(e){var n="250%";"undefined"==typeof Focus?e.Focus=function(){console.log("Initializing focus.js...");var e={};return e.init=function(e){elID=e.elementID,n=e.zoomFactor||"250%",console.log(n,e.zoomFactor);var o=(""!==elID?document.getElementById(elID):document).querySelectorAll(".focus-img");Array.from(o).forEach(function(e){e.addEventListener("mouseenter",function(e){this.style.backgroundSize=n},!1),e.addEventListener("mousemove",function(e){var n=this.getBoundingClientRect(),o=e.clientX-n.left,t=e.clientY-n.top,i=Math.round(100/(n.width/o)),c=Math.round(100/(n.height/t));this.style.backgroundPosition=i+"% "+c+"%"},!1),e.addEventListener("mouseleave",function(e){this.style.backgroundPosition="center",this.style.backgroundSize="cover"},!1)})},e}():console.log("focus.js has been initialized already.")}(window);;
/*! Select2 4.0.6-rc.0 | https://github.com/select2/select2/blob/master/LICENSE.md */!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):"object"==typeof module&&module.exports?module.exports=function(b,c){return void 0===c&&(c="undefined"!=typeof window?require("jquery"):require("jquery")(b)),a(c),c}:a(jQuery)}(function(a){var b=function(){if(a&&a.fn&&a.fn.select2&&a.fn.select2.amd)var b=a.fn.select2.amd;var b;return function(){if(!b||!b.requirejs){b?c=b:b={};var a,c,d;!function(b){function e(a,b){return v.call(a,b)}function f(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o=b&&b.split("/"),p=t.map,q=p&&p["*"]||{};if(a){for(a=a.split("/"),g=a.length-1,t.nodeIdCompat&&x.test(a[g])&&(a[g]=a[g].replace(x,"")),"."===a[0].charAt(0)&&o&&(n=o.slice(0,o.length-1),a=n.concat(a)),k=0;k<a.length;k++)if("."===(m=a[k]))a.splice(k,1),k-=1;else if(".."===m){if(0===k||1===k&&".."===a[2]||".."===a[k-1])continue;k>0&&(a.splice(k-1,2),k-=2)}a=a.join("/")}if((o||q)&&p){for(c=a.split("/"),k=c.length;k>0;k-=1){if(d=c.slice(0,k).join("/"),o)for(l=o.length;l>0;l-=1)if((e=p[o.slice(0,l).join("/")])&&(e=e[d])){f=e,h=k;break}if(f)break;!i&&q&&q[d]&&(i=q[d],j=k)}!f&&i&&(f=i,h=j),f&&(c.splice(0,h,f),a=c.join("/"))}return a}function g(a,c){return function(){var d=w.call(arguments,0);return"string"!=typeof d[0]&&1===d.length&&d.push(null),o.apply(b,d.concat([a,c]))}}function h(a){return function(b){return f(b,a)}}function i(a){return function(b){r[a]=b}}function j(a){if(e(s,a)){var c=s[a];delete s[a],u[a]=!0,n.apply(b,c)}if(!e(r,a)&&!e(u,a))throw new Error("No "+a);return r[a]}function k(a){var b,c=a?a.indexOf("!"):-1;return c>-1&&(b=a.substring(0,c),a=a.substring(c+1,a.length)),[b,a]}function l(a){return a?k(a):[]}function m(a){return function(){return t&&t.config&&t.config[a]||{}}}var n,o,p,q,r={},s={},t={},u={},v=Object.prototype.hasOwnProperty,w=[].slice,x=/\.js$/;p=function(a,b){var c,d=k(a),e=d[0],g=b[1];return a=d[1],e&&(e=f(e,g),c=j(e)),e?a=c&&c.normalize?c.normalize(a,h(g)):f(a,g):(a=f(a,g),d=k(a),e=d[0],a=d[1],e&&(c=j(e))),{f:e?e+"!"+a:a,n:a,pr:e,p:c}},q={require:function(a){return g(a)},exports:function(a){var b=r[a];return void 0!==b?b:r[a]={}},module:function(a){return{id:a,uri:"",exports:r[a],config:m(a)}}},n=function(a,c,d,f){var h,k,m,n,o,t,v,w=[],x=typeof d;if(f=f||a,t=l(f),"undefined"===x||"function"===x){for(c=!c.length&&d.length?["require","exports","module"]:c,o=0;o<c.length;o+=1)if(n=p(c[o],t),"require"===(k=n.f))w[o]=q.require(a);else if("exports"===k)w[o]=q.exports(a),v=!0;else if("module"===k)h=w[o]=q.module(a);else if(e(r,k)||e(s,k)||e(u,k))w[o]=j(k);else{if(!n.p)throw new Error(a+" missing "+k);n.p.load(n.n,g(f,!0),i(k),{}),w[o]=r[k]}m=d?d.apply(r[a],w):void 0,a&&(h&&h.exports!==b&&h.exports!==r[a]?r[a]=h.exports:m===b&&v||(r[a]=m))}else a&&(r[a]=d)},a=c=o=function(a,c,d,e,f){if("string"==typeof a)return q[a]?q[a](c):j(p(a,l(c)).f);if(!a.splice){if(t=a,t.deps&&o(t.deps,t.callback),!c)return;c.splice?(a=c,c=d,d=null):a=b}return c=c||function(){},"function"==typeof d&&(d=e,e=f),e?n(b,a,c,d):setTimeout(function(){n(b,a,c,d)},4),o},o.config=function(a){return o(a)},a._defined=r,d=function(a,b,c){if("string"!=typeof a)throw new Error("See almond README: incorrect module build, no module name");b.splice||(c=b,b=[]),e(r,a)||e(s,a)||(s[a]=[a,b,c])},d.amd={jQuery:!0}}(),b.requirejs=a,b.require=c,b.define=d}}(),b.define("almond",function(){}),b.define("jquery",[],function(){var b=a||$;return null==b&&console&&console.error&&console.error("Select2: An instance of jQuery or a jQuery-compatible library was not found. Make sure that you are including jQuery before Select2 on your web page."),b}),b.define("select2/utils",["jquery"],function(a){function b(a){var b=a.prototype,c=[];for(var d in b){"function"==typeof b[d]&&("constructor"!==d&&c.push(d))}return c}var c={};c.Extend=function(a,b){function c(){this.constructor=a}var d={}.hasOwnProperty;for(var e in b)d.call(b,e)&&(a[e]=b[e]);return c.prototype=b.prototype,a.prototype=new c,a.__super__=b.prototype,a},c.Decorate=function(a,c){function d(){var b=Array.prototype.unshift,d=c.prototype.constructor.length,e=a.prototype.constructor;d>0&&(b.call(arguments,a.prototype.constructor),e=c.prototype.constructor),e.apply(this,arguments)}function e(){this.constructor=d}var f=b(c),g=b(a);c.displayName=a.displayName,d.prototype=new e;for(var h=0;h<g.length;h++){var i=g[h];d.prototype[i]=a.prototype[i]}for(var j=(function(a){var b=function(){};a in d.prototype&&(b=d.prototype[a]);var e=c.prototype[a];return function(){return Array.prototype.unshift.call(arguments,b),e.apply(this,arguments)}}),k=0;k<f.length;k++){var l=f[k];d.prototype[l]=j(l)}return d};var d=function(){this.listeners={}};d.prototype.on=function(a,b){this.listeners=this.listeners||{},a in this.listeners?this.listeners[a].push(b):this.listeners[a]=[b]},d.prototype.trigger=function(a){var b=Array.prototype.slice,c=b.call(arguments,1);this.listeners=this.listeners||{},null==c&&(c=[]),0===c.length&&c.push({}),c[0]._type=a,a in this.listeners&&this.invoke(this.listeners[a],b.call(arguments,1)),"*"in this.listeners&&this.invoke(this.listeners["*"],arguments)},d.prototype.invoke=function(a,b){for(var c=0,d=a.length;c<d;c++)a[c].apply(this,b)},c.Observable=d,c.generateChars=function(a){for(var b="",c=0;c<a;c++){b+=Math.floor(36*Math.random()).toString(36)}return b},c.bind=function(a,b){return function(){a.apply(b,arguments)}},c._convertData=function(a){for(var b in a){var c=b.split("-"),d=a;if(1!==c.length){for(var e=0;e<c.length;e++){var f=c[e];f=f.substring(0,1).toLowerCase()+f.substring(1),f in d||(d[f]={}),e==c.length-1&&(d[f]=a[b]),d=d[f]}delete a[b]}}return a},c.hasScroll=function(b,c){var d=a(c),e=c.style.overflowX,f=c.style.overflowY;return(e!==f||"hidden"!==f&&"visible"!==f)&&("scroll"===e||"scroll"===f||(d.innerHeight()<c.scrollHeight||d.innerWidth()<c.scrollWidth))},c.escapeMarkup=function(a){var b={"\\":"&#92;","&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#47;"};return"string"!=typeof a?a:String(a).replace(/[&<>"'\/\\]/g,function(a){return b[a]})},c.appendMany=function(b,c){if("1.7"===a.fn.jquery.substr(0,3)){var d=a();a.map(c,function(a){d=d.add(a)}),c=d}b.append(c)},c.__cache={};var e=0;return c.GetUniqueElementId=function(a){var b=a.getAttribute("data-select2-id");return null==b&&(a.id?(b=a.id,a.setAttribute("data-select2-id",b)):(a.setAttribute("data-select2-id",++e),b=e.toString())),b},c.StoreData=function(a,b,d){var e=c.GetUniqueElementId(a);c.__cache[e]||(c.__cache[e]={}),c.__cache[e][b]=d},c.GetData=function(b,d){var e=c.GetUniqueElementId(b);return d?c.__cache[e]&&null!=c.__cache[e][d]?c.__cache[e][d]:a(b).data(d):c.__cache[e]},c.RemoveData=function(a){var b=c.GetUniqueElementId(a);null!=c.__cache[b]&&delete c.__cache[b]},c}),b.define("select2/results",["jquery","./utils"],function(a,b){function c(a,b,d){this.$element=a,this.data=d,this.options=b,c.__super__.constructor.call(this)}return b.Extend(c,b.Observable),c.prototype.render=function(){var b=a('<ul class="select2-results__options" role="tree"></ul>');return this.options.get("multiple")&&b.attr("aria-multiselectable","true"),this.$results=b,b},c.prototype.clear=function(){this.$results.empty()},c.prototype.displayMessage=function(b){var c=this.options.get("escapeMarkup");this.clear(),this.hideLoading();var d=a('<li role="treeitem" aria-live="assertive" class="select2-results__option"></li>'),e=this.options.get("translations").get(b.message);d.append(c(e(b.args))),d[0].className+=" select2-results__message",this.$results.append(d)},c.prototype.hideMessages=function(){this.$results.find(".select2-results__message").remove()},c.prototype.append=function(a){this.hideLoading();var b=[];if(null==a.results||0===a.results.length)return void(0===this.$results.children().length&&this.trigger("results:message",{message:"noResults"}));a.results=this.sort(a.results);for(var c=0;c<a.results.length;c++){var d=a.results[c],e=this.option(d);b.push(e)}this.$results.append(b)},c.prototype.position=function(a,b){b.find(".select2-results").append(a)},c.prototype.sort=function(a){return this.options.get("sorter")(a)},c.prototype.highlightFirstItem=function(){var a=this.$results.find(".select2-results__option[aria-selected]"),b=a.filter("[aria-selected=true]");b.length>0?b.first().trigger("mouseenter"):a.first().trigger("mouseenter"),this.ensureHighlightVisible()},c.prototype.setClasses=function(){var c=this;this.data.current(function(d){var e=a.map(d,function(a){return a.id.toString()});c.$results.find(".select2-results__option[aria-selected]").each(function(){var c=a(this),d=b.GetData(this,"data"),f=""+d.id;null!=d.element&&d.element.selected||null==d.element&&a.inArray(f,e)>-1?c.attr("aria-selected","true"):c.attr("aria-selected","false")})})},c.prototype.showLoading=function(a){this.hideLoading();var b=this.options.get("translations").get("searching"),c={disabled:!0,loading:!0,text:b(a)},d=this.option(c);d.className+=" loading-results",this.$results.prepend(d)},c.prototype.hideLoading=function(){this.$results.find(".loading-results").remove()},c.prototype.option=function(c){var d=document.createElement("li");d.className="select2-results__option";var e={role:"treeitem","aria-selected":"false"};c.disabled&&(delete e["aria-selected"],e["aria-disabled"]="true"),null==c.id&&delete e["aria-selected"],null!=c._resultId&&(d.id=c._resultId),c.title&&(d.title=c.title),c.children&&(e.role="group",e["aria-label"]=c.text,delete e["aria-selected"]);for(var f in e){var g=e[f];d.setAttribute(f,g)}if(c.children){var h=a(d),i=document.createElement("strong");i.className="select2-results__group";a(i);this.template(c,i);for(var j=[],k=0;k<c.children.length;k++){var l=c.children[k],m=this.option(l);j.push(m)}var n=a("<ul></ul>",{class:"select2-results__options select2-results__options--nested"});n.append(j),h.append(i),h.append(n)}else this.template(c,d);return b.StoreData(d,"data",c),d},c.prototype.bind=function(c,d){var e=this,f=c.id+"-results";this.$results.attr("id",f),c.on("results:all",function(a){e.clear(),e.append(a.data),c.isOpen()&&(e.setClasses(),e.highlightFirstItem())}),c.on("results:append",function(a){e.append(a.data),c.isOpen()&&e.setClasses()}),c.on("query",function(a){e.hideMessages(),e.showLoading(a)}),c.on("select",function(){c.isOpen()&&(e.setClasses(),e.highlightFirstItem())}),c.on("unselect",function(){c.isOpen()&&(e.setClasses(),e.highlightFirstItem())}),c.on("open",function(){e.$results.attr("aria-expanded","true"),e.$results.attr("aria-hidden","false"),e.setClasses(),e.ensureHighlightVisible()}),c.on("close",function(){e.$results.attr("aria-expanded","false"),e.$results.attr("aria-hidden","true"),e.$results.removeAttr("aria-activedescendant")}),c.on("results:toggle",function(){var a=e.getHighlightedResults();0!==a.length&&a.trigger("mouseup")}),c.on("results:select",function(){var a=e.getHighlightedResults();if(0!==a.length){var c=b.GetData(a[0],"data");"true"==a.attr("aria-selected")?e.trigger("close",{}):e.trigger("select",{data:c})}}),c.on("results:previous",function(){var a=e.getHighlightedResults(),b=e.$results.find("[aria-selected]"),c=b.index(a);if(0!==c){var d=c-1;0===a.length&&(d=0);var f=b.eq(d);f.trigger("mouseenter");var g=e.$results.offset().top,h=f.offset().top,i=e.$results.scrollTop()+(h-g);0===d?e.$results.scrollTop(0):h-g<0&&e.$results.scrollTop(i)}}),c.on("results:next",function(){var a=e.getHighlightedResults(),b=e.$results.find("[aria-selected]"),c=b.index(a),d=c+1;if(!(d>=b.length)){var f=b.eq(d);f.trigger("mouseenter");var g=e.$results.offset().top+e.$results.outerHeight(!1),h=f.offset().top+f.outerHeight(!1),i=e.$results.scrollTop()+h-g;0===d?e.$results.scrollTop(0):h>g&&e.$results.scrollTop(i)}}),c.on("results:focus",function(a){a.element.addClass("select2-results__option--highlighted")}),c.on("results:message",function(a){e.displayMessage(a)}),a.fn.mousewheel&&this.$results.on("mousewheel",function(a){var b=e.$results.scrollTop(),c=e.$results.get(0).scrollHeight-b+a.deltaY,d=a.deltaY>0&&b-a.deltaY<=0,f=a.deltaY<0&&c<=e.$results.height();d?(e.$results.scrollTop(0),a.preventDefault(),a.stopPropagation()):f&&(e.$results.scrollTop(e.$results.get(0).scrollHeight-e.$results.height()),a.preventDefault(),a.stopPropagation())}),this.$results.on("mouseup",".select2-results__option[aria-selected]",function(c){var d=a(this),f=b.GetData(this,"data");if("true"===d.attr("aria-selected"))return void(e.options.get("multiple")?e.trigger("unselect",{originalEvent:c,data:f}):e.trigger("close",{}));e.trigger("select",{originalEvent:c,data:f})}),this.$results.on("mouseenter",".select2-results__option[aria-selected]",function(c){var d=b.GetData(this,"data");e.getHighlightedResults().removeClass("select2-results__option--highlighted"),e.trigger("results:focus",{data:d,element:a(this)})})},c.prototype.getHighlightedResults=function(){return this.$results.find(".select2-results__option--highlighted")},c.prototype.destroy=function(){this.$results.remove()},c.prototype.ensureHighlightVisible=function(){var a=this.getHighlightedResults();if(0!==a.length){var b=this.$results.find("[aria-selected]"),c=b.index(a),d=this.$results.offset().top,e=a.offset().top,f=this.$results.scrollTop()+(e-d),g=e-d;f-=2*a.outerHeight(!1),c<=2?this.$results.scrollTop(0):(g>this.$results.outerHeight()||g<0)&&this.$results.scrollTop(f)}},c.prototype.template=function(b,c){var d=this.options.get("templateResult"),e=this.options.get("escapeMarkup"),f=d(b,c);null==f?c.style.display="none":"string"==typeof f?c.innerHTML=e(f):a(c).append(f)},c}),b.define("select2/keys",[],function(){return{BACKSPACE:8,TAB:9,ENTER:13,SHIFT:16,CTRL:17,ALT:18,ESC:27,SPACE:32,PAGE_UP:33,PAGE_DOWN:34,END:35,HOME:36,LEFT:37,UP:38,RIGHT:39,DOWN:40,DELETE:46}}),b.define("select2/selection/base",["jquery","../utils","../keys"],function(a,b,c){function d(a,b){this.$element=a,this.options=b,d.__super__.constructor.call(this)}return b.Extend(d,b.Observable),d.prototype.render=function(){var c=a('<span class="select2-selection" role="combobox"  aria-haspopup="true" aria-expanded="false"></span>');return this._tabindex=0,null!=b.GetData(this.$element[0],"old-tabindex")?this._tabindex=b.GetData(this.$element[0],"old-tabindex"):null!=this.$element.attr("tabindex")&&(this._tabindex=this.$element.attr("tabindex")),c.attr("title",this.$element.attr("title")),c.attr("tabindex",this._tabindex),this.$selection=c,c},d.prototype.bind=function(a,b){var d=this,e=(a.id,a.id+"-results");this.container=a,this.$selection.on("focus",function(a){d.trigger("focus",a)}),this.$selection.on("blur",function(a){d._handleBlur(a)}),this.$selection.on("keydown",function(a){d.trigger("keypress",a),a.which===c.SPACE&&a.preventDefault()}),a.on("results:focus",function(a){d.$selection.attr("aria-activedescendant",a.data._resultId)}),a.on("selection:update",function(a){d.update(a.data)}),a.on("open",function(){d.$selection.attr("aria-expanded","true"),d.$selection.attr("aria-owns",e),d._attachCloseHandler(a)}),a.on("close",function(){d.$selection.attr("aria-expanded","false"),d.$selection.removeAttr("aria-activedescendant"),d.$selection.removeAttr("aria-owns"),d.$selection.focus(),d._detachCloseHandler(a)}),a.on("enable",function(){d.$selection.attr("tabindex",d._tabindex)}),a.on("disable",function(){d.$selection.attr("tabindex","-1")})},d.prototype._handleBlur=function(b){var c=this;window.setTimeout(function(){document.activeElement==c.$selection[0]||a.contains(c.$selection[0],document.activeElement)||c.trigger("blur",b)},1)},d.prototype._attachCloseHandler=function(c){a(document.body).on("mousedown.select2."+c.id,function(c){var d=a(c.target),e=d.closest(".select2");a(".select2.select2-container--open").each(function(){a(this),this!=e[0]&&b.GetData(this,"element").select2("close")})})},d.prototype._detachCloseHandler=function(b){a(document.body).off("mousedown.select2."+b.id)},d.prototype.position=function(a,b){b.find(".selection").append(a)},d.prototype.destroy=function(){this._detachCloseHandler(this.container)},d.prototype.update=function(a){throw new Error("The `update` method must be defined in child classes.")},d}),b.define("select2/selection/single",["jquery","./base","../utils","../keys"],function(a,b,c,d){function e(){e.__super__.constructor.apply(this,arguments)}return c.Extend(e,b),e.prototype.render=function(){var a=e.__super__.render.call(this);return a.addClass("select2-selection--single"),a.html('<span class="select2-selection__rendered"></span><span class="select2-selection__arrow" role="presentation"><b role="presentation"></b></span>'),a},e.prototype.bind=function(a,b){var c=this;e.__super__.bind.apply(this,arguments);var d=a.id+"-container";this.$selection.find(".select2-selection__rendered").attr("id",d).attr("role","textbox").attr("aria-readonly","true"),this.$selection.attr("aria-labelledby",d),this.$selection.on("mousedown",function(a){1===a.which&&c.trigger("toggle",{originalEvent:a})}),this.$selection.on("focus",function(a){}),this.$selection.on("blur",function(a){}),a.on("focus",function(b){a.isOpen()||c.$selection.focus()})},e.prototype.clear=function(){var a=this.$selection.find(".select2-selection__rendered");a.empty(),a.removeAttr("title")},e.prototype.display=function(a,b){var c=this.options.get("templateSelection");return this.options.get("escapeMarkup")(c(a,b))},e.prototype.selectionContainer=function(){return a("<span></span>")},e.prototype.update=function(a){if(0===a.length)return void this.clear();var b=a[0],c=this.$selection.find(".select2-selection__rendered"),d=this.display(b,c);c.empty().append(d),c.attr("title",b.title||b.text)},e}),b.define("select2/selection/multiple",["jquery","./base","../utils"],function(a,b,c){function d(a,b){d.__super__.constructor.apply(this,arguments)}return c.Extend(d,b),d.prototype.render=function(){var a=d.__super__.render.call(this);return a.addClass("select2-selection--multiple"),a.html('<ul class="select2-selection__rendered"></ul>'),a},d.prototype.bind=function(b,e){var f=this;d.__super__.bind.apply(this,arguments),this.$selection.on("click",function(a){f.trigger("toggle",{originalEvent:a})}),this.$selection.on("click",".select2-selection__choice__remove",function(b){if(!f.options.get("disabled")){var d=a(this),e=d.parent(),g=c.GetData(e[0],"data");f.trigger("unselect",{originalEvent:b,data:g})}})},d.prototype.clear=function(){var a=this.$selection.find(".select2-selection__rendered");a.empty(),a.removeAttr("title")},d.prototype.display=function(a,b){var c=this.options.get("templateSelection");return this.options.get("escapeMarkup")(c(a,b))},d.prototype.selectionContainer=function(){return a('<li class="select2-selection__choice"><span class="select2-selection__choice__remove" role="presentation">&times;</span></li>')},d.prototype.update=function(a){if(this.clear(),0!==a.length){for(var b=[],d=0;d<a.length;d++){var e=a[d],f=this.selectionContainer(),g=this.display(e,f);f.append(g),f.attr("title",e.title||e.text),c.StoreData(f[0],"data",e),b.push(f)}var h=this.$selection.find(".select2-selection__rendered");c.appendMany(h,b)}},d}),b.define("select2/selection/placeholder",["../utils"],function(a){function b(a,b,c){this.placeholder=this.normalizePlaceholder(c.get("placeholder")),a.call(this,b,c)}return b.prototype.normalizePlaceholder=function(a,b){return"string"==typeof b&&(b={id:"",text:b}),b},b.prototype.createPlaceholder=function(a,b){var c=this.selectionContainer();return c.html(this.display(b)),c.addClass("select2-selection__placeholder").removeClass("select2-selection__choice"),c},b.prototype.update=function(a,b){var c=1==b.length&&b[0].id!=this.placeholder.id;if(b.length>1||c)return a.call(this,b);this.clear();var d=this.createPlaceholder(this.placeholder);this.$selection.find(".select2-selection__rendered").append(d)},b}),b.define("select2/selection/allowClear",["jquery","../keys","../utils"],function(a,b,c){function d(){}return d.prototype.bind=function(a,b,c){var d=this;a.call(this,b,c),null==this.placeholder&&this.options.get("debug")&&window.console&&console.error&&console.error("Select2: The `allowClear` option should be used in combination with the `placeholder` option."),this.$selection.on("mousedown",".select2-selection__clear",function(a){d._handleClear(a)}),b.on("keypress",function(a){d._handleKeyboardClear(a,b)})},d.prototype._handleClear=function(a,b){if(!this.options.get("disabled")){var d=this.$selection.find(".select2-selection__clear");if(0!==d.length){b.stopPropagation();var e=c.GetData(d[0],"data"),f=this.$element.val();this.$element.val(this.placeholder.id);var g={data:e};if(this.trigger("clear",g),g.prevented)return void this.$element.val(f);for(var h=0;h<e.length;h++)if(g={data:e[h]},this.trigger("unselect",g),g.prevented)return void this.$element.val(f);this.$element.trigger("change"),this.trigger("toggle",{})}}},d.prototype._handleKeyboardClear=function(a,c,d){d.isOpen()||c.which!=b.DELETE&&c.which!=b.BACKSPACE||this._handleClear(c)},d.prototype.update=function(b,d){if(b.call(this,d),!(this.$selection.find(".select2-selection__placeholder").length>0||0===d.length)){var e=a('<span class="select2-selection__clear">&times;</span>');c.StoreData(e[0],"data",d),this.$selection.find(".select2-selection__rendered").prepend(e)}},d}),b.define("select2/selection/search",["jquery","../utils","../keys"],function(a,b,c){function d(a,b,c){a.call(this,b,c)}return d.prototype.render=function(b){var c=a('<li class="select2-search select2-search--inline"><input class="select2-search__field" type="search" tabindex="-1" autocomplete="off" autocorrect="off" autocapitalize="none" spellcheck="false" role="textbox" aria-autocomplete="list" /></li>');this.$searchContainer=c,this.$search=c.find("input");var d=b.call(this);return this._transferTabIndex(),d},d.prototype.bind=function(a,d,e){var f=this;a.call(this,d,e),d.on("open",function(){f.$search.trigger("focus")}),d.on("close",function(){f.$search.val(""),f.$search.removeAttr("aria-activedescendant"),f.$search.trigger("focus")}),d.on("enable",function(){f.$search.prop("disabled",!1),f._transferTabIndex()}),d.on("disable",function(){f.$search.prop("disabled",!0)}),d.on("focus",function(a){f.$search.trigger("focus")}),d.on("results:focus",function(a){f.$search.attr("aria-activedescendant",a.id)}),this.$selection.on("focusin",".select2-search--inline",function(a){f.trigger("focus",a)}),this.$selection.on("focusout",".select2-search--inline",function(a){f._handleBlur(a)}),this.$selection.on("keydown",".select2-search--inline",function(a){if(a.stopPropagation(),f.trigger("keypress",a),f._keyUpPrevented=a.isDefaultPrevented(),a.which===c.BACKSPACE&&""===f.$search.val()){var d=f.$searchContainer.prev(".select2-selection__choice");if(d.length>0){var e=b.GetData(d[0],"data");f.searchRemoveChoice(e),a.preventDefault()}}});var g=document.documentMode,h=g&&g<=11;this.$selection.on("input.searchcheck",".select2-search--inline",function(a){if(h)return void f.$selection.off("input.search input.searchcheck");f.$selection.off("keyup.search")}),this.$selection.on("keyup.search input.search",".select2-search--inline",function(a){if(h&&"input"===a.type)return void f.$selection.off("input.search input.searchcheck");var b=a.which;b!=c.SHIFT&&b!=c.CTRL&&b!=c.ALT&&b!=c.TAB&&f.handleSearch(a)})},d.prototype._transferTabIndex=function(a){this.$search.attr("tabindex",this.$selection.attr("tabindex")),this.$selection.attr("tabindex","-1")},d.prototype.createPlaceholder=function(a,b){this.$search.attr("placeholder",b.text)},d.prototype.update=function(a,b){var c=this.$search[0]==document.activeElement;this.$search.attr("placeholder",""),a.call(this,b),this.$selection.find(".select2-selection__rendered").append(this.$searchContainer),this.resizeSearch(),c&&this.$search.focus()},d.prototype.handleSearch=function(){if(this.resizeSearch(),!this._keyUpPrevented){var a=this.$search.val();this.trigger("query",{term:a})}this._keyUpPrevented=!1},d.prototype.searchRemoveChoice=function(a,b){this.trigger("unselect",{data:b}),this.$search.val(b.text),this.handleSearch()},d.prototype.resizeSearch=function(){this.$search.css("width","25px");var a="";if(""!==this.$search.attr("placeholder"))a=this.$selection.find(".select2-selection__rendered").innerWidth();else{a=.75*(this.$search.val().length+1)+"em"}this.$search.css("width",a)},d}),b.define("select2/selection/eventRelay",["jquery"],function(a){function b(){}return b.prototype.bind=function(b,c,d){var e=this,f=["open","opening","close","closing","select","selecting","unselect","unselecting","clear","clearing"],g=["opening","closing","selecting","unselecting","clearing"];b.call(this,c,d),c.on("*",function(b,c){if(-1!==a.inArray(b,f)){c=c||{};var d=a.Event("select2:"+b,{params:c});e.$element.trigger(d),-1!==a.inArray(b,g)&&(c.prevented=d.isDefaultPrevented())}})},b}),b.define("select2/translation",["jquery","require"],function(a,b){function c(a){this.dict=a||{}}return c.prototype.all=function(){return this.dict},c.prototype.get=function(a){return this.dict[a]},c.prototype.extend=function(b){this.dict=a.extend({},b.all(),this.dict)},c._cache={},c.loadPath=function(a){if(!(a in c._cache)){var d=b(a);c._cache[a]=d}return new c(c._cache[a])},c}),b.define("select2/diacritics",[],function(){return{"Ⓐ":"A","Ａ":"A","À":"A","Á":"A","Â":"A","Ầ":"A","Ấ":"A","Ẫ":"A","Ẩ":"A","Ã":"A","Ā":"A","Ă":"A","Ằ":"A","Ắ":"A","Ẵ":"A","Ẳ":"A","Ȧ":"A","Ǡ":"A","Ä":"A","Ǟ":"A","Ả":"A","Å":"A","Ǻ":"A","Ǎ":"A","Ȁ":"A","Ȃ":"A","Ạ":"A","Ậ":"A","Ặ":"A","Ḁ":"A","Ą":"A","Ⱥ":"A","Ɐ":"A","Ꜳ":"AA","Æ":"AE","Ǽ":"AE","Ǣ":"AE","Ꜵ":"AO","Ꜷ":"AU","Ꜹ":"AV","Ꜻ":"AV","Ꜽ":"AY","Ⓑ":"B","Ｂ":"B","Ḃ":"B","Ḅ":"B","Ḇ":"B","Ƀ":"B","Ƃ":"B","Ɓ":"B","Ⓒ":"C","Ｃ":"C","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","Ç":"C","Ḉ":"C","Ƈ":"C","Ȼ":"C","Ꜿ":"C","Ⓓ":"D","Ｄ":"D","Ḋ":"D","Ď":"D","Ḍ":"D","Ḑ":"D","Ḓ":"D","Ḏ":"D","Đ":"D","Ƌ":"D","Ɗ":"D","Ɖ":"D","Ꝺ":"D","Ǳ":"DZ","Ǆ":"DZ","ǲ":"Dz","ǅ":"Dz","Ⓔ":"E","Ｅ":"E","È":"E","É":"E","Ê":"E","Ề":"E","Ế":"E","Ễ":"E","Ể":"E","Ẽ":"E","Ē":"E","Ḕ":"E","Ḗ":"E","Ĕ":"E","Ė":"E","Ë":"E","Ẻ":"E","Ě":"E","Ȅ":"E","Ȇ":"E","Ẹ":"E","Ệ":"E","Ȩ":"E","Ḝ":"E","Ę":"E","Ḙ":"E","Ḛ":"E","Ɛ":"E","Ǝ":"E","Ⓕ":"F","Ｆ":"F","Ḟ":"F","Ƒ":"F","Ꝼ":"F","Ⓖ":"G","Ｇ":"G","Ǵ":"G","Ĝ":"G","Ḡ":"G","Ğ":"G","Ġ":"G","Ǧ":"G","Ģ":"G","Ǥ":"G","Ɠ":"G","Ꞡ":"G","Ᵹ":"G","Ꝿ":"G","Ⓗ":"H","Ｈ":"H","Ĥ":"H","Ḣ":"H","Ḧ":"H","Ȟ":"H","Ḥ":"H","Ḩ":"H","Ḫ":"H","Ħ":"H","Ⱨ":"H","Ⱶ":"H","Ɥ":"H","Ⓘ":"I","Ｉ":"I","Ì":"I","Í":"I","Î":"I","Ĩ":"I","Ī":"I","Ĭ":"I","İ":"I","Ï":"I","Ḯ":"I","Ỉ":"I","Ǐ":"I","Ȉ":"I","Ȋ":"I","Ị":"I","Į":"I","Ḭ":"I","Ɨ":"I","Ⓙ":"J","Ｊ":"J","Ĵ":"J","Ɉ":"J","Ⓚ":"K","Ｋ":"K","Ḱ":"K","Ǩ":"K","Ḳ":"K","Ķ":"K","Ḵ":"K","Ƙ":"K","Ⱪ":"K","Ꝁ":"K","Ꝃ":"K","Ꝅ":"K","Ꞣ":"K","Ⓛ":"L","Ｌ":"L","Ŀ":"L","Ĺ":"L","Ľ":"L","Ḷ":"L","Ḹ":"L","Ļ":"L","Ḽ":"L","Ḻ":"L","Ł":"L","Ƚ":"L","Ɫ":"L","Ⱡ":"L","Ꝉ":"L","Ꝇ":"L","Ꞁ":"L","Ǉ":"LJ","ǈ":"Lj","Ⓜ":"M","Ｍ":"M","Ḿ":"M","Ṁ":"M","Ṃ":"M","Ɱ":"M","Ɯ":"M","Ⓝ":"N","Ｎ":"N","Ǹ":"N","Ń":"N","Ñ":"N","Ṅ":"N","Ň":"N","Ṇ":"N","Ņ":"N","Ṋ":"N","Ṉ":"N","Ƞ":"N","Ɲ":"N","Ꞑ":"N","Ꞥ":"N","Ǌ":"NJ","ǋ":"Nj","Ⓞ":"O","Ｏ":"O","Ò":"O","Ó":"O","Ô":"O","Ồ":"O","Ố":"O","Ỗ":"O","Ổ":"O","Õ":"O","Ṍ":"O","Ȭ":"O","Ṏ":"O","Ō":"O","Ṑ":"O","Ṓ":"O","Ŏ":"O","Ȯ":"O","Ȱ":"O","Ö":"O","Ȫ":"O","Ỏ":"O","Ő":"O","Ǒ":"O","Ȍ":"O","Ȏ":"O","Ơ":"O","Ờ":"O","Ớ":"O","Ỡ":"O","Ở":"O","Ợ":"O","Ọ":"O","Ộ":"O","Ǫ":"O","Ǭ":"O","Ø":"O","Ǿ":"O","Ɔ":"O","Ɵ":"O","Ꝋ":"O","Ꝍ":"O","Ƣ":"OI","Ꝏ":"OO","Ȣ":"OU","Ⓟ":"P","Ｐ":"P","Ṕ":"P","Ṗ":"P","Ƥ":"P","Ᵽ":"P","Ꝑ":"P","Ꝓ":"P","Ꝕ":"P","Ⓠ":"Q","Ｑ":"Q","Ꝗ":"Q","Ꝙ":"Q","Ɋ":"Q","Ⓡ":"R","Ｒ":"R","Ŕ":"R","Ṙ":"R","Ř":"R","Ȑ":"R","Ȓ":"R","Ṛ":"R","Ṝ":"R","Ŗ":"R","Ṟ":"R","Ɍ":"R","Ɽ":"R","Ꝛ":"R","Ꞧ":"R","Ꞃ":"R","Ⓢ":"S","Ｓ":"S","ẞ":"S","Ś":"S","Ṥ":"S","Ŝ":"S","Ṡ":"S","Š":"S","Ṧ":"S","Ṣ":"S","Ṩ":"S","Ș":"S","Ş":"S","Ȿ":"S","Ꞩ":"S","Ꞅ":"S","Ⓣ":"T","Ｔ":"T","Ṫ":"T","Ť":"T","Ṭ":"T","Ț":"T","Ţ":"T","Ṱ":"T","Ṯ":"T","Ŧ":"T","Ƭ":"T","Ʈ":"T","Ⱦ":"T","Ꞇ":"T","Ꜩ":"TZ","Ⓤ":"U","Ｕ":"U","Ù":"U","Ú":"U","Û":"U","Ũ":"U","Ṹ":"U","Ū":"U","Ṻ":"U","Ŭ":"U","Ü":"U","Ǜ":"U","Ǘ":"U","Ǖ":"U","Ǚ":"U","Ủ":"U","Ů":"U","Ű":"U","Ǔ":"U","Ȕ":"U","Ȗ":"U","Ư":"U","Ừ":"U","Ứ":"U","Ữ":"U","Ử":"U","Ự":"U","Ụ":"U","Ṳ":"U","Ų":"U","Ṷ":"U","Ṵ":"U","Ʉ":"U","Ⓥ":"V","Ｖ":"V","Ṽ":"V","Ṿ":"V","Ʋ":"V","Ꝟ":"V","Ʌ":"V","Ꝡ":"VY","Ⓦ":"W","Ｗ":"W","Ẁ":"W","Ẃ":"W","Ŵ":"W","Ẇ":"W","Ẅ":"W","Ẉ":"W","Ⱳ":"W","Ⓧ":"X","Ｘ":"X","Ẋ":"X","Ẍ":"X","Ⓨ":"Y","Ｙ":"Y","Ỳ":"Y","Ý":"Y","Ŷ":"Y","Ỹ":"Y","Ȳ":"Y","Ẏ":"Y","Ÿ":"Y","Ỷ":"Y","Ỵ":"Y","Ƴ":"Y","Ɏ":"Y","Ỿ":"Y","Ⓩ":"Z","Ｚ":"Z","Ź":"Z","Ẑ":"Z","Ż":"Z","Ž":"Z","Ẓ":"Z","Ẕ":"Z","Ƶ":"Z","Ȥ":"Z","Ɀ":"Z","Ⱬ":"Z","Ꝣ":"Z","ⓐ":"a","ａ":"a","ẚ":"a","à":"a","á":"a","â":"a","ầ":"a","ấ":"a","ẫ":"a","ẩ":"a","ã":"a","ā":"a","ă":"a","ằ":"a","ắ":"a","ẵ":"a","ẳ":"a","ȧ":"a","ǡ":"a","ä":"a","ǟ":"a","ả":"a","å":"a","ǻ":"a","ǎ":"a","ȁ":"a","ȃ":"a","ạ":"a","ậ":"a","ặ":"a","ḁ":"a","ą":"a","ⱥ":"a","ɐ":"a","ꜳ":"aa","æ":"ae","ǽ":"ae","ǣ":"ae","ꜵ":"ao","ꜷ":"au","ꜹ":"av","ꜻ":"av","ꜽ":"ay","ⓑ":"b","ｂ":"b","ḃ":"b","ḅ":"b","ḇ":"b","ƀ":"b","ƃ":"b","ɓ":"b","ⓒ":"c","ｃ":"c","ć":"c","ĉ":"c","ċ":"c","č":"c","ç":"c","ḉ":"c","ƈ":"c","ȼ":"c","ꜿ":"c","ↄ":"c","ⓓ":"d","ｄ":"d","ḋ":"d","ď":"d","ḍ":"d","ḑ":"d","ḓ":"d","ḏ":"d","đ":"d","ƌ":"d","ɖ":"d","ɗ":"d","ꝺ":"d","ǳ":"dz","ǆ":"dz","ⓔ":"e","ｅ":"e","è":"e","é":"e","ê":"e","ề":"e","ế":"e","ễ":"e","ể":"e","ẽ":"e","ē":"e","ḕ":"e","ḗ":"e","ĕ":"e","ė":"e","ë":"e","ẻ":"e","ě":"e","ȅ":"e","ȇ":"e","ẹ":"e","ệ":"e","ȩ":"e","ḝ":"e","ę":"e","ḙ":"e","ḛ":"e","ɇ":"e","ɛ":"e","ǝ":"e","ⓕ":"f","ｆ":"f","ḟ":"f","ƒ":"f","ꝼ":"f","ⓖ":"g","ｇ":"g","ǵ":"g","ĝ":"g","ḡ":"g","ğ":"g","ġ":"g","ǧ":"g","ģ":"g","ǥ":"g","ɠ":"g","ꞡ":"g","ᵹ":"g","ꝿ":"g","ⓗ":"h","ｈ":"h","ĥ":"h","ḣ":"h","ḧ":"h","ȟ":"h","ḥ":"h","ḩ":"h","ḫ":"h","ẖ":"h","ħ":"h","ⱨ":"h","ⱶ":"h","ɥ":"h","ƕ":"hv","ⓘ":"i","ｉ":"i","ì":"i","í":"i","î":"i","ĩ":"i","ī":"i","ĭ":"i","ï":"i","ḯ":"i","ỉ":"i","ǐ":"i","ȉ":"i","ȋ":"i","ị":"i","į":"i","ḭ":"i","ɨ":"i","ı":"i","ⓙ":"j","ｊ":"j","ĵ":"j","ǰ":"j","ɉ":"j","ⓚ":"k","ｋ":"k","ḱ":"k","ǩ":"k","ḳ":"k","ķ":"k","ḵ":"k","ƙ":"k","ⱪ":"k","ꝁ":"k","ꝃ":"k","ꝅ":"k","ꞣ":"k","ⓛ":"l","ｌ":"l","ŀ":"l","ĺ":"l","ľ":"l","ḷ":"l","ḹ":"l","ļ":"l","ḽ":"l","ḻ":"l","ſ":"l","ł":"l","ƚ":"l","ɫ":"l","ⱡ":"l","ꝉ":"l","ꞁ":"l","ꝇ":"l","ǉ":"lj","ⓜ":"m","ｍ":"m","ḿ":"m","ṁ":"m","ṃ":"m","ɱ":"m","ɯ":"m","ⓝ":"n","ｎ":"n","ǹ":"n","ń":"n","ñ":"n","ṅ":"n","ň":"n","ṇ":"n","ņ":"n","ṋ":"n","ṉ":"n","ƞ":"n","ɲ":"n","ŉ":"n","ꞑ":"n","ꞥ":"n","ǌ":"nj","ⓞ":"o","ｏ":"o","ò":"o","ó":"o","ô":"o","ồ":"o","ố":"o","ỗ":"o","ổ":"o","õ":"o","ṍ":"o","ȭ":"o","ṏ":"o","ō":"o","ṑ":"o","ṓ":"o","ŏ":"o","ȯ":"o","ȱ":"o","ö":"o","ȫ":"o","ỏ":"o","ő":"o","ǒ":"o","ȍ":"o","ȏ":"o","ơ":"o","ờ":"o","ớ":"o","ỡ":"o","ở":"o","ợ":"o","ọ":"o","ộ":"o","ǫ":"o","ǭ":"o","ø":"o","ǿ":"o","ɔ":"o","ꝋ":"o","ꝍ":"o","ɵ":"o","ƣ":"oi","ȣ":"ou","ꝏ":"oo","ⓟ":"p","ｐ":"p","ṕ":"p","ṗ":"p","ƥ":"p","ᵽ":"p","ꝑ":"p","ꝓ":"p","ꝕ":"p","ⓠ":"q","ｑ":"q","ɋ":"q","ꝗ":"q","ꝙ":"q","ⓡ":"r","ｒ":"r","ŕ":"r","ṙ":"r","ř":"r","ȑ":"r","ȓ":"r","ṛ":"r","ṝ":"r","ŗ":"r","ṟ":"r","ɍ":"r","ɽ":"r","ꝛ":"r","ꞧ":"r","ꞃ":"r","ⓢ":"s","ｓ":"s","ß":"s","ś":"s","ṥ":"s","ŝ":"s","ṡ":"s","š":"s","ṧ":"s","ṣ":"s","ṩ":"s","ș":"s","ş":"s","ȿ":"s","ꞩ":"s","ꞅ":"s","ẛ":"s","ⓣ":"t","ｔ":"t","ṫ":"t","ẗ":"t","ť":"t","ṭ":"t","ț":"t","ţ":"t","ṱ":"t","ṯ":"t","ŧ":"t","ƭ":"t","ʈ":"t","ⱦ":"t","ꞇ":"t","ꜩ":"tz","ⓤ":"u","ｕ":"u","ù":"u","ú":"u","û":"u","ũ":"u","ṹ":"u","ū":"u","ṻ":"u","ŭ":"u","ü":"u","ǜ":"u","ǘ":"u","ǖ":"u","ǚ":"u","ủ":"u","ů":"u","ű":"u","ǔ":"u","ȕ":"u","ȗ":"u","ư":"u","ừ":"u","ứ":"u","ữ":"u","ử":"u","ự":"u","ụ":"u","ṳ":"u","ų":"u","ṷ":"u","ṵ":"u","ʉ":"u","ⓥ":"v","ｖ":"v","ṽ":"v","ṿ":"v","ʋ":"v","ꝟ":"v","ʌ":"v","ꝡ":"vy","ⓦ":"w","ｗ":"w","ẁ":"w","ẃ":"w","ŵ":"w","ẇ":"w","ẅ":"w","ẘ":"w","ẉ":"w","ⱳ":"w","ⓧ":"x","ｘ":"x","ẋ":"x","ẍ":"x","ⓨ":"y","ｙ":"y","ỳ":"y","ý":"y","ŷ":"y","ỹ":"y","ȳ":"y","ẏ":"y","ÿ":"y","ỷ":"y","ẙ":"y","ỵ":"y","ƴ":"y","ɏ":"y","ỿ":"y","ⓩ":"z","ｚ":"z","ź":"z","ẑ":"z","ż":"z","ž":"z","ẓ":"z","ẕ":"z","ƶ":"z","ȥ":"z","ɀ":"z","ⱬ":"z","ꝣ":"z","Ά":"Α","Έ":"Ε","Ή":"Η","Ί":"Ι","Ϊ":"Ι","Ό":"Ο","Ύ":"Υ","Ϋ":"Υ","Ώ":"Ω","ά":"α","έ":"ε","ή":"η","ί":"ι","ϊ":"ι","ΐ":"ι","ό":"ο","ύ":"υ","ϋ":"υ","ΰ":"υ","ω":"ω","ς":"σ"}}),b.define("select2/data/base",["../utils"],function(a){function b(a,c){b.__super__.constructor.call(this)}return a.Extend(b,a.Observable),b.prototype.current=function(a){throw new Error("The `current` method must be defined in child classes.")},b.prototype.query=function(a,b){throw new Error("The `query` method must be defined in child classes.")},b.prototype.bind=function(a,b){},b.prototype.destroy=function(){},b.prototype.generateResultId=function(b,c){var d=b.id+"-result-";return d+=a.generateChars(4),null!=c.id?d+="-"+c.id.toString():d+="-"+a.generateChars(4),d},b}),b.define("select2/data/select",["./base","../utils","jquery"],function(a,b,c){function d(a,b){this.$element=a,this.options=b,d.__super__.constructor.call(this)}return b.Extend(d,a),d.prototype.current=function(a){var b=[],d=this;this.$element.find(":selected").each(function(){var a=c(this),e=d.item(a);b.push(e)}),a(b)},d.prototype.select=function(a){var b=this;if(a.selected=!0,c(a.element).is("option"))return a.element.selected=!0,void this.$element.trigger("change");if(this.$element.prop("multiple"))this.current(function(d){var e=[];a=[a],a.push.apply(a,d);for(var f=0;f<a.length;f++){var g=a[f].id;-1===c.inArray(g,e)&&e.push(g)}b.$element.val(e),b.$element.trigger("change")});else{var d=a.id;this.$element.val(d),this.$element.trigger("change")}},d.prototype.unselect=function(a){var b=this;if(this.$element.prop("multiple")){if(a.selected=!1,c(a.element).is("option"))return a.element.selected=!1,void this.$element.trigger("change");this.current(function(d){for(var e=[],f=0;f<d.length;f++){var g=d[f].id;g!==a.id&&-1===c.inArray(g,e)&&e.push(g)}b.$element.val(e),b.$element.trigger("change")})}},d.prototype.bind=function(a,b){var c=this;this.container=a,a.on("select",function(a){c.select(a.data)}),a.on("unselect",function(a){c.unselect(a.data)})},d.prototype.destroy=function(){this.$element.find("*").each(function(){b.RemoveData(this)})},d.prototype.query=function(a,b){var d=[],e=this;this.$element.children().each(function(){var b=c(this);if(b.is("option")||b.is("optgroup")){var f=e.item(b),g=e.matches(a,f);null!==g&&d.push(g)}}),b({results:d})},d.prototype.addOptions=function(a){b.appendMany(this.$element,a)},d.prototype.option=function(a){var d;a.children?(d=document.createElement("optgroup"),d.label=a.text):(d=document.createElement("option"),void 0!==d.textContent?d.textContent=a.text:d.innerText=a.text),void 0!==a.id&&(d.value=a.id),a.disabled&&(d.disabled=!0),a.selected&&(d.selected=!0),a.title&&(d.title=a.title);var e=c(d),f=this._normalizeItem(a);return f.element=d,b.StoreData(d,"data",f),e},d.prototype.item=function(a){var d={};if(null!=(d=b.GetData(a[0],"data")))return d;if(a.is("option"))d={id:a.val(),text:a.text(),disabled:a.prop("disabled"),selected:a.prop("selected"),title:a.prop("title")};else if(a.is("optgroup")){d={text:a.prop("label"),children:[],title:a.prop("title")};for(var e=a.children("option"),f=[],g=0;g<e.length;g++){var h=c(e[g]),i=this.item(h);f.push(i)}d.children=f}return d=this._normalizeItem(d),d.element=a[0],b.StoreData(a[0],"data",d),d},d.prototype._normalizeItem=function(a){a!==Object(a)&&(a={id:a,text:a}),a=c.extend({},{text:""},a);var b={selected:!1,disabled:!1};return null!=a.id&&(a.id=a.id.toString()),null!=a.text&&(a.text=a.text.toString()),null==a._resultId&&a.id&&null!=this.container&&(a._resultId=this.generateResultId(this.container,a)),c.extend({},b,a)},d.prototype.matches=function(a,b){return this.options.get("matcher")(a,b)},d}),b.define("select2/data/array",["./select","../utils","jquery"],function(a,b,c){function d(a,b){var c=b.get("data")||[];d.__super__.constructor.call(this,a,b),this.addOptions(this.convertToOptions(c))}return b.Extend(d,a),d.prototype.select=function(a){var b=this.$element.find("option").filter(function(b,c){return c.value==a.id.toString()});0===b.length&&(b=this.option(a),this.addOptions(b)),d.__super__.select.call(this,a)},d.prototype.convertToOptions=function(a){function d(a){return function(){return c(this).val()==a.id}}for(var e=this,f=this.$element.find("option"),g=f.map(function(){return e.item(c(this)).id}).get(),h=[],i=0;i<a.length;i++){var j=this._normalizeItem(a[i]);if(c.inArray(j.id,g)>=0){var k=f.filter(d(j)),l=this.item(k),m=c.extend(!0,{},j,l),n=this.option(m);k.replaceWith(n)}else{var o=this.option(j);if(j.children){var p=this.convertToOptions(j.children);b.appendMany(o,p)}h.push(o)}}return h},d}),b.define("select2/data/ajax",["./array","../utils","jquery"],function(a,b,c){function d(a,b){this.ajaxOptions=this._applyDefaults(b.get("ajax")),null!=this.ajaxOptions.processResults&&(this.processResults=this.ajaxOptions.processResults),d.__super__.constructor.call(this,a,b)}return b.Extend(d,a),d.prototype._applyDefaults=function(a){var b={data:function(a){return c.extend({},a,{q:a.term})},transport:function(a,b,d){var e=c.ajax(a);return e.then(b),e.fail(d),e}};return c.extend({},b,a,!0)},d.prototype.processResults=function(a){return a},d.prototype.query=function(a,b){function d(){var d=f.transport(f,function(d){var f=e.processResults(d,a);e.options.get("debug")&&window.console&&console.error&&(f&&f.results&&c.isArray(f.results)||console.error("Select2: The AJAX results did not return an array in the `results` key of the response.")),b(f)},function(){"status"in d&&(0===d.status||"0"===d.status)||e.trigger("results:message",{message:"errorLoading"})});e._request=d}var e=this;null!=this._request&&(c.isFunction(this._request.abort)&&this._request.abort(),this._request=null);var f=c.extend({type:"GET"},this.ajaxOptions);"function"==typeof f.url&&(f.url=f.url.call(this.$element,a)),"function"==typeof f.data&&(f.data=f.data.call(this.$element,a)),this.ajaxOptions.delay&&null!=a.term?(this._queryTimeout&&window.clearTimeout(this._queryTimeout),this._queryTimeout=window.setTimeout(d,this.ajaxOptions.delay)):d()},d}),b.define("select2/data/tags",["jquery"],function(a){function b(b,c,d){var e=d.get("tags"),f=d.get("createTag");void 0!==f&&(this.createTag=f);var g=d.get("insertTag");if(void 0!==g&&(this.insertTag=g),b.call(this,c,d),a.isArray(e))for(var h=0;h<e.length;h++){var i=e[h],j=this._normalizeItem(i),k=this.option(j);this.$element.append(k)}}return b.prototype.query=function(a,b,c){function d(a,f){for(var g=a.results,h=0;h<g.length;h++){var i=g[h],j=null!=i.children&&!d({results:i.children},!0);if((i.text||"").toUpperCase()===(b.term||"").toUpperCase()||j)return!f&&(a.data=g,void c(a))}if(f)return!0;var k=e.createTag(b);if(null!=k){var l=e.option(k);l.attr("data-select2-tag",!0),e.addOptions([l]),e.insertTag(g,k)}a.results=g,c(a)}var e=this;if(this._removeOldTags(),null==b.term||null!=b.page)return void a.call(this,b,c);a.call(this,b,d)},b.prototype.createTag=function(b,c){var d=a.trim(c.term);return""===d?null:{id:d,text:d}},b.prototype.insertTag=function(a,b,c){b.unshift(c)},b.prototype._removeOldTags=function(b){this._lastTag;this.$element.find("option[data-select2-tag]").each(function(){this.selected||a(this).remove()})},b}),b.define("select2/data/tokenizer",["jquery"],function(a){function b(a,b,c){var d=c.get("tokenizer");void 0!==d&&(this.tokenizer=d),a.call(this,b,c)}return b.prototype.bind=function(a,b,c){a.call(this,b,c),this.$search=b.dropdown.$search||b.selection.$search||c.find(".select2-search__field")},b.prototype.query=function(b,c,d){function e(b){var c=g._normalizeItem(b);if(!g.$element.find("option").filter(function(){return a(this).val()===c.id}).length){var d=g.option(c);d.attr("data-select2-tag",!0),g._removeOldTags(),g.addOptions([d])}f(c)}function f(a){g.trigger("select",{data:a})}var g=this;c.term=c.term||"";var h=this.tokenizer(c,this.options,e);h.term!==c.term&&(this.$search.length&&(this.$search.val(h.term),this.$search.focus()),c.term=h.term),b.call(this,c,d)},b.prototype.tokenizer=function(b,c,d,e){for(var f=d.get("tokenSeparators")||[],g=c.term,h=0,i=this.createTag||function(a){return{id:a.term,text:a.term}};h<g.length;){var j=g[h];if(-1!==a.inArray(j,f)){var k=g.substr(0,h),l=a.extend({},c,{term:k}),m=i(l);null!=m?(e(m),g=g.substr(h+1)||"",h=0):h++}else h++}return{term:g}},b}),b.define("select2/data/minimumInputLength",[],function(){function a(a,b,c){this.minimumInputLength=c.get("minimumInputLength"),a.call(this,b,c)}return a.prototype.query=function(a,b,c){if(b.term=b.term||"",b.term.length<this.minimumInputLength)return void this.trigger("results:message",{message:"inputTooShort",args:{minimum:this.minimumInputLength,input:b.term,params:b}});a.call(this,b,c)},a}),b.define("select2/data/maximumInputLength",[],function(){function a(a,b,c){this.maximumInputLength=c.get("maximumInputLength"),a.call(this,b,c)}return a.prototype.query=function(a,b,c){if(b.term=b.term||"",this.maximumInputLength>0&&b.term.length>this.maximumInputLength)return void this.trigger("results:message",{message:"inputTooLong",args:{maximum:this.maximumInputLength,input:b.term,params:b}});a.call(this,b,c)},a}),b.define("select2/data/maximumSelectionLength",[],function(){function a(a,b,c){this.maximumSelectionLength=c.get("maximumSelectionLength"),a.call(this,b,c)}return a.prototype.query=function(a,b,c){var d=this;this.current(function(e){var f=null!=e?e.length:0;if(d.maximumSelectionLength>0&&f>=d.maximumSelectionLength)return void d.trigger("results:message",{message:"maximumSelected",args:{maximum:d.maximumSelectionLength}});a.call(d,b,c)})},a}),b.define("select2/dropdown",["jquery","./utils"],function(a,b){function c(a,b){this.$element=a,this.options=b,c.__super__.constructor.call(this)}return b.Extend(c,b.Observable),c.prototype.render=function(){var b=a('<span class="select2-dropdown"><span class="select2-results"></span></span>');return b.attr("dir",this.options.get("dir")),this.$dropdown=b,b},c.prototype.bind=function(){},c.prototype.position=function(a,b){},c.prototype.destroy=function(){this.$dropdown.remove()},c}),b.define("select2/dropdown/search",["jquery","../utils"],function(a,b){function c(){}return c.prototype.render=function(b){var c=b.call(this),d=a('<span class="select2-search select2-search--dropdown"><input class="select2-search__field" type="search" tabindex="-1" autocomplete="off" autocorrect="off" autocapitalize="none" spellcheck="false" role="textbox" /></span>');return this.$searchContainer=d,this.$search=d.find("input"),c.prepend(d),c},c.prototype.bind=function(b,c,d){var e=this;b.call(this,c,d),this.$search.on("keydown",function(a){e.trigger("keypress",a),e._keyUpPrevented=a.isDefaultPrevented()}),this.$search.on("input",function(b){a(this).off("keyup")}),this.$search.on("keyup input",function(a){e.handleSearch(a)}),c.on("open",function(){e.$search.attr("tabindex",0),e.$search.focus(),window.setTimeout(function(){e.$search.focus()},0)}),c.on("close",function(){e.$search.attr("tabindex",-1),e.$search.val(""),e.$search.blur()}),c.on("focus",function(){c.isOpen()||e.$search.focus()}),c.on("results:all",function(a){if(null==a.query.term||""===a.query.term){e.showSearch(a)?e.$searchContainer.removeClass("select2-search--hide"):e.$searchContainer.addClass("select2-search--hide")}})},c.prototype.handleSearch=function(a){if(!this._keyUpPrevented){var b=this.$search.val();this.trigger("query",{term:b})}this._keyUpPrevented=!1},c.prototype.showSearch=function(a,b){return!0},c}),b.define("select2/dropdown/hidePlaceholder",[],function(){function a(a,b,c,d){this.placeholder=this.normalizePlaceholder(c.get("placeholder")),a.call(this,b,c,d)}return a.prototype.append=function(a,b){b.results=this.removePlaceholder(b.results),a.call(this,b)},a.prototype.normalizePlaceholder=function(a,b){return"string"==typeof b&&(b={id:"",text:b}),b},a.prototype.removePlaceholder=function(a,b){for(var c=b.slice(0),d=b.length-1;d>=0;d--){var e=b[d];this.placeholder.id===e.id&&c.splice(d,1)}return c},a}),b.define("select2/dropdown/infiniteScroll",["jquery"],function(a){function b(a,b,c,d){this.lastParams={},a.call(this,b,c,d),this.$loadingMore=this.createLoadingMore(),this.loading=!1}return b.prototype.append=function(a,b){this.$loadingMore.remove(),this.loading=!1,a.call(this,b),this.showLoadingMore(b)&&this.$results.append(this.$loadingMore)},b.prototype.bind=function(b,c,d){var e=this;b.call(this,c,d),c.on("query",function(a){e.lastParams=a,e.loading=!0}),c.on("query:append",function(a){e.lastParams=a,e.loading=!0}),this.$results.on("scroll",function(){var b=a.contains(document.documentElement,e.$loadingMore[0]);if(!e.loading&&b){e.$results.offset().top+e.$results.outerHeight(!1)+50>=e.$loadingMore.offset().top+e.$loadingMore.outerHeight(!1)&&e.loadMore()}})},b.prototype.loadMore=function(){this.loading=!0;var b=a.extend({},{page:1},this.lastParams);b.page++,this.trigger("query:append",b)},b.prototype.showLoadingMore=function(a,b){return b.pagination&&b.pagination.more},b.prototype.createLoadingMore=function(){var b=a('<li class="select2-results__option select2-results__option--load-more"role="treeitem" aria-disabled="true"></li>'),c=this.options.get("translations").get("loadingMore");return b.html(c(this.lastParams)),b},b}),b.define("select2/dropdown/attachBody",["jquery","../utils"],function(a,b){function c(b,c,d){this.$dropdownParent=d.get("dropdownParent")||a(document.body),b.call(this,c,d)}return c.prototype.bind=function(a,b,c){var d=this,e=!1;a.call(this,b,c),b.on("open",function(){d._showDropdown(),d._attachPositioningHandler(b),e||(e=!0,b.on("results:all",function(){d._positionDropdown(),d._resizeDropdown()}),b.on("results:append",function(){d._positionDropdown(),d._resizeDropdown()}))}),b.on("close",function(){d._hideDropdown(),d._detachPositioningHandler(b)}),this.$dropdownContainer.on("mousedown",function(a){a.stopPropagation()})},c.prototype.destroy=function(a){a.call(this),this.$dropdownContainer.remove()},c.prototype.position=function(a,b,c){b.attr("class",c.attr("class")),b.removeClass("select2"),b.addClass("select2-container--open"),b.css({position:"absolute",top:-999999}),this.$container=c},c.prototype.render=function(b){var c=a("<span></span>"),d=b.call(this);return c.append(d),this.$dropdownContainer=c,c},c.prototype._hideDropdown=function(a){this.$dropdownContainer.detach()},c.prototype._attachPositioningHandler=function(c,d){var e=this,f="scroll.select2."+d.id,g="resize.select2."+d.id,h="orientationchange.select2."+d.id,i=this.$container.parents().filter(b.hasScroll);i.each(function(){b.StoreData(this,"select2-scroll-position",{x:a(this).scrollLeft(),y:a(this).scrollTop()})}),i.on(f,function(c){var d=b.GetData(this,"select2-scroll-position");a(this).scrollTop(d.y)}),a(window).on(f+" "+g+" "+h,function(a){e._positionDropdown(),e._resizeDropdown()})},c.prototype._detachPositioningHandler=function(c,d){var e="scroll.select2."+d.id,f="resize.select2."+d.id,g="orientationchange.select2."+d.id;this.$container.parents().filter(b.hasScroll).off(e),a(window).off(e+" "+f+" "+g)},c.prototype._positionDropdown=function(){var b=a(window),c=this.$dropdown.hasClass("select2-dropdown--above"),d=this.$dropdown.hasClass("select2-dropdown--below"),e=null,f=this.$container.offset();f.bottom=f.top+this.$container.outerHeight(!1);var g={height:this.$container.outerHeight(!1)};g.top=f.top,g.bottom=f.top+g.height;var h={height:this.$dropdown.outerHeight(!1)},i={top:b.scrollTop(),bottom:b.scrollTop()+b.height()},j=i.top<f.top-h.height,k=i.bottom>f.bottom+h.height,l={left:f.left,top:g.bottom},m=this.$dropdownParent;"static"===m.css("position")&&(m=m.offsetParent());var n=m.offset();l.top-=n.top,l.left-=n.left,c||d||(e="below"),k||!j||c?!j&&k&&c&&(e="below"):e="above",("above"==e||c&&"below"!==e)&&(l.top=g.top-n.top-h.height),null!=e&&(this.$dropdown.removeClass("select2-dropdown--below select2-dropdown--above").addClass("select2-dropdown--"+e),this.$container.removeClass("select2-container--below select2-container--above").addClass("select2-container--"+e)),this.$dropdownContainer.css(l)},c.prototype._resizeDropdown=function(){var a={width:this.$container.outerWidth(!1)+"px"};this.options.get("dropdownAutoWidth")&&(a.minWidth=a.width,a.position="relative",a.width="auto"),this.$dropdown.css(a)},c.prototype._showDropdown=function(a){this.$dropdownContainer.appendTo(this.$dropdownParent),this._positionDropdown(),this._resizeDropdown()},c}),b.define("select2/dropdown/minimumResultsForSearch",[],function(){function a(b){for(var c=0,d=0;d<b.length;d++){var e=b[d];e.children?c+=a(e.children):c++}return c}function b(a,b,c,d){this.minimumResultsForSearch=c.get("minimumResultsForSearch"),this.minimumResultsForSearch<0&&(this.minimumResultsForSearch=1/0),a.call(this,b,c,d)}return b.prototype.showSearch=function(b,c){return!(a(c.data.results)<this.minimumResultsForSearch)&&b.call(this,c)},b}),b.define("select2/dropdown/selectOnClose",["../utils"],function(a){function b(){}return b.prototype.bind=function(a,b,c){var d=this;a.call(this,b,c),b.on("close",function(a){d._handleSelectOnClose(a)})},b.prototype._handleSelectOnClose=function(b,c){if(c&&null!=c.originalSelect2Event){var d=c.originalSelect2Event;if("select"===d._type||"unselect"===d._type)return}var e=this.getHighlightedResults();if(!(e.length<1)){var f=a.GetData(e[0],"data");null!=f.element&&f.element.selected||null==f.element&&f.selected||this.trigger("select",{data:f})}},b}),b.define("select2/dropdown/closeOnSelect",[],function(){function a(){}return a.prototype.bind=function(a,b,c){var d=this;a.call(this,b,c),b.on("select",function(a){d._selectTriggered(a)}),b.on("unselect",function(a){d._selectTriggered(a)})},a.prototype._selectTriggered=function(a,b){var c=b.originalEvent;c&&c.ctrlKey||this.trigger("close",{originalEvent:c,originalSelect2Event:b})},a}),b.define("select2/i18n/en",[],function(){return{errorLoading:function(){return"The results could not be loaded."},inputTooLong:function(a){var b=a.input.length-a.maximum,c="Please delete "+b+" character";return 1!=b&&(c+="s"),c},inputTooShort:function(a){return"Please enter "+(a.minimum-a.input.length)+" or more characters"},loadingMore:function(){return"Loading more results…"},maximumSelected:function(a){var b="You can only select "+a.maximum+" item";return 1!=a.maximum&&(b+="s"),b},noResults:function(){return"No results found"},searching:function(){return"Searching…"}}}),b.define("select2/defaults",["jquery","require","./results","./selection/single","./selection/multiple","./selection/placeholder","./selection/allowClear","./selection/search","./selection/eventRelay","./utils","./translation","./diacritics","./data/select","./data/array","./data/ajax","./data/tags","./data/tokenizer","./data/minimumInputLength","./data/maximumInputLength","./data/maximumSelectionLength","./dropdown","./dropdown/search","./dropdown/hidePlaceholder","./dropdown/infiniteScroll","./dropdown/attachBody","./dropdown/minimumResultsForSearch","./dropdown/selectOnClose","./dropdown/closeOnSelect","./i18n/en"],function(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,A,B,C){function D(){this.reset()}return D.prototype.apply=function(l){if(l=a.extend(!0,{},this.defaults,l),null==l.dataAdapter){if(null!=l.ajax?l.dataAdapter=o:null!=l.data?l.dataAdapter=n:l.dataAdapter=m,l.minimumInputLength>0&&(l.dataAdapter=j.Decorate(l.dataAdapter,r)),l.maximumInputLength>0&&(l.dataAdapter=j.Decorate(l.dataAdapter,s)),l.maximumSelectionLength>0&&(l.dataAdapter=j.Decorate(l.dataAdapter,t)),l.tags&&(l.dataAdapter=j.Decorate(l.dataAdapter,p)),null==l.tokenSeparators&&null==l.tokenizer||(l.dataAdapter=j.Decorate(l.dataAdapter,q)),null!=l.query){var C=b(l.amdBase+"compat/query");l.dataAdapter=j.Decorate(l.dataAdapter,C)}if(null!=l.initSelection){var D=b(l.amdBase+"compat/initSelection");l.dataAdapter=j.Decorate(l.dataAdapter,D)}}if(null==l.resultsAdapter&&(l.resultsAdapter=c,null!=l.ajax&&(l.resultsAdapter=j.Decorate(l.resultsAdapter,x)),null!=l.placeholder&&(l.resultsAdapter=j.Decorate(l.resultsAdapter,w)),l.selectOnClose&&(l.resultsAdapter=j.Decorate(l.resultsAdapter,A))),null==l.dropdownAdapter){if(l.multiple)l.dropdownAdapter=u;else{var E=j.Decorate(u,v);l.dropdownAdapter=E}if(0!==l.minimumResultsForSearch&&(l.dropdownAdapter=j.Decorate(l.dropdownAdapter,z)),l.closeOnSelect&&(l.dropdownAdapter=j.Decorate(l.dropdownAdapter,B)),null!=l.dropdownCssClass||null!=l.dropdownCss||null!=l.adaptDropdownCssClass){var F=b(l.amdBase+"compat/dropdownCss");l.dropdownAdapter=j.Decorate(l.dropdownAdapter,F)}l.dropdownAdapter=j.Decorate(l.dropdownAdapter,y)}if(null==l.selectionAdapter){if(l.multiple?l.selectionAdapter=e:l.selectionAdapter=d,null!=l.placeholder&&(l.selectionAdapter=j.Decorate(l.selectionAdapter,f)),l.allowClear&&(l.selectionAdapter=j.Decorate(l.selectionAdapter,g)),l.multiple&&(l.selectionAdapter=j.Decorate(l.selectionAdapter,h)),null!=l.containerCssClass||null!=l.containerCss||null!=l.adaptContainerCssClass){var G=b(l.amdBase+"compat/containerCss");l.selectionAdapter=j.Decorate(l.selectionAdapter,G)}l.selectionAdapter=j.Decorate(l.selectionAdapter,i)}if("string"==typeof l.language)if(l.language.indexOf("-")>0){var H=l.language.split("-"),I=H[0];l.language=[l.language,I]}else l.language=[l.language];if(a.isArray(l.language)){var J=new k;l.language.push("en");for(var K=l.language,L=0;L<K.length;L++){var M=K[L],N={};try{N=k.loadPath(M)}catch(a){try{M=this.defaults.amdLanguageBase+M,N=k.loadPath(M)}catch(a){l.debug&&window.console&&console.warn&&console.warn('Select2: The language file for "'+M+'" could not be automatically loaded. A fallback will be used instead.');continue}}J.extend(N)}l.translations=J}else{var O=k.loadPath(this.defaults.amdLanguageBase+"en"),P=new k(l.language);P.extend(O),l.translations=P}return l},D.prototype.reset=function(){function b(a){function b(a){return l[a]||a}return a.replace(/[^\u0000-\u007E]/g,b)}function c(d,e){if(""===a.trim(d.term))return e;if(e.children&&e.children.length>0){for(var f=a.extend(!0,{},e),g=e.children.length-1;g>=0;g--){null==c(d,e.children[g])&&f.children.splice(g,1)}return f.children.length>0?f:c(d,f)}var h=b(e.text).toUpperCase(),i=b(d.term).toUpperCase();return h.indexOf(i)>-1?e:null}this.defaults={amdBase:"./",amdLanguageBase:"./i18n/",closeOnSelect:!0,debug:!1,dropdownAutoWidth:!1,escapeMarkup:j.escapeMarkup,language:C,matcher:c,minimumInputLength:0,maximumInputLength:0,maximumSelectionLength:0,minimumResultsForSearch:0,selectOnClose:!1,sorter:function(a){return a},templateResult:function(a){return a.text},templateSelection:function(a){return a.text},theme:"default",width:"resolve"}},D.prototype.set=function(b,c){var d=a.camelCase(b),e={};e[d]=c;var f=j._convertData(e);a.extend(!0,this.defaults,f)},new D}),b.define("select2/options",["require","jquery","./defaults","./utils"],function(a,b,c,d){function e(b,e){if(this.options=b,null!=e&&this.fromElement(e),this.options=c.apply(this.options),e&&e.is("input")){var f=a(this.get("amdBase")+"compat/inputData");this.options.dataAdapter=d.Decorate(this.options.dataAdapter,f)}}return e.prototype.fromElement=function(a){var c=["select2"];null==this.options.multiple&&(this.options.multiple=a.prop("multiple")),null==this.options.disabled&&(this.options.disabled=a.prop("disabled")),null==this.options.language&&(a.prop("lang")?this.options.language=a.prop("lang").toLowerCase():a.closest("[lang]").prop("lang")&&(this.options.language=a.closest("[lang]").prop("lang"))),null==this.options.dir&&(a.prop("dir")?this.options.dir=a.prop("dir"):a.closest("[dir]").prop("dir")?this.options.dir=a.closest("[dir]").prop("dir"):this.options.dir="ltr"),a.prop("disabled",this.options.disabled),a.prop("multiple",this.options.multiple),d.GetData(a[0],"select2Tags")&&(this.options.debug&&window.console&&console.warn&&console.warn('Select2: The `data-select2-tags` attribute has been changed to use the `data-data` and `data-tags="true"` attributes and will be removed in future versions of Select2.'),d.StoreData(a[0],"data",d.GetData(a[0],"select2Tags")),d.StoreData(a[0],"tags",!0)),d.GetData(a[0],"ajaxUrl")&&(this.options.debug&&window.console&&console.warn&&console.warn("Select2: The `data-ajax-url` attribute has been changed to `data-ajax--url` and support for the old attribute will be removed in future versions of Select2."),a.attr("ajax--url",d.GetData(a[0],"ajaxUrl")),d.StoreData(a[0],"ajax-Url",d.GetData(a[0],"ajaxUrl")));var e={};e=b.fn.jquery&&"1."==b.fn.jquery.substr(0,2)&&a[0].dataset?b.extend(!0,{},a[0].dataset,d.GetData(a[0])):d.GetData(a[0]);var f=b.extend(!0,{},e);f=d._convertData(f);for(var g in f)b.inArray(g,c)>-1||(b.isPlainObject(this.options[g])?b.extend(this.options[g],f[g]):this.options[g]=f[g]);return this},e.prototype.get=function(a){return this.options[a]},e.prototype.set=function(a,b){this.options[a]=b},e}),b.define("select2/core",["jquery","./options","./utils","./keys"],function(a,b,c,d){var e=function(a,d){null!=c.GetData(a[0],"select2")&&c.GetData(a[0],"select2").destroy(),this.$element=a,this.id=this._generateId(a),d=d||{},this.options=new b(d,a),e.__super__.constructor.call(this);var f=a.attr("tabindex")||0;c.StoreData(a[0],"old-tabindex",f),a.attr("tabindex","-1");var g=this.options.get("dataAdapter");this.dataAdapter=new g(a,this.options);var h=this.render();this._placeContainer(h);var i=this.options.get("selectionAdapter");this.selection=new i(a,this.options),this.$selection=this.selection.render(),this.selection.position(this.$selection,h);var j=this.options.get("dropdownAdapter");this.dropdown=new j(a,this.options),this.$dropdown=this.dropdown.render(),this.dropdown.position(this.$dropdown,h);var k=this.options.get("resultsAdapter");this.results=new k(a,this.options,this.dataAdapter),this.$results=this.results.render(),this.results.position(this.$results,this.$dropdown);var l=this;this._bindAdapters(),this._registerDomEvents(),this._registerDataEvents(),this._registerSelectionEvents(),this._registerDropdownEvents(),this._registerResultsEvents(),this._registerEvents(),this.dataAdapter.current(function(a){l.trigger("selection:update",{data:a})}),a.addClass("select2-hidden-accessible"),a.attr("aria-hidden","true"),this._syncAttributes(),c.StoreData(a[0],"select2",this)};return c.Extend(e,c.Observable),e.prototype._generateId=function(a){var b="";return b=null!=a.attr("id")?a.attr("id"):null!=a.attr("name")?a.attr("name")+"-"+c.generateChars(2):c.generateChars(4),b=b.replace(/(:|\.|\[|\]|,)/g,""),b="select2-"+b},e.prototype._placeContainer=function(a){a.insertAfter(this.$element);var b=this._resolveWidth(this.$element,this.options.get("width"));null!=b&&a.css("width",b)},e.prototype._resolveWidth=function(a,b){var c=/^width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/i;if("resolve"==b){var d=this._resolveWidth(a,"style");return null!=d?d:this._resolveWidth(a,"element")}if("element"==b){var e=a.outerWidth(!1);return e<=0?"auto":e+"px"}if("style"==b){var f=a.attr("style");if("string"!=typeof f)return null;for(var g=f.split(";"),h=0,i=g.length;h<i;h+=1){var j=g[h].replace(/\s/g,""),k=j.match(c);if(null!==k&&k.length>=1)return k[1]}return null}return b},e.prototype._bindAdapters=function(){this.dataAdapter.bind(this,this.$container),this.selection.bind(this,this.$container),this.dropdown.bind(this,this.$container),this.results.bind(this,this.$container)},e.prototype._registerDomEvents=function(){var b=this;this.$element.on("change.select2",function(){b.dataAdapter.current(function(a){b.trigger("selection:update",{data:a})})}),this.$element.on("focus.select2",function(a){b.trigger("focus",a)}),this._syncA=c.bind(this._syncAttributes,this),this._syncS=c.bind(this._syncSubtree,this),this.$element[0].attachEvent&&this.$element[0].attachEvent("onpropertychange",this._syncA);var d=window.MutationObserver||window.WebKitMutationObserver||window.MozMutationObserver;null!=d?(this._observer=new d(function(c){a.each(c,b._syncA),a.each(c,b._syncS)}),this._observer.observe(this.$element[0],{attributes:!0,childList:!0,subtree:!1})):this.$element[0].addEventListener&&(this.$element[0].addEventListener("DOMAttrModified",b._syncA,!1),this.$element[0].addEventListener("DOMNodeInserted",b._syncS,!1),this.$element[0].addEventListener("DOMNodeRemoved",b._syncS,!1))},e.prototype._registerDataEvents=function(){var a=this;this.dataAdapter.on("*",function(b,c){a.trigger(b,c)})},e.prototype._registerSelectionEvents=function(){var b=this,c=["toggle","focus"];this.selection.on("toggle",function(){b.toggleDropdown()}),this.selection.on("focus",function(a){b.focus(a)}),this.selection.on("*",function(d,e){-1===a.inArray(d,c)&&b.trigger(d,e)})},e.prototype._registerDropdownEvents=function(){var a=this;this.dropdown.on("*",function(b,c){a.trigger(b,c)})},e.prototype._registerResultsEvents=function(){var a=this;this.results.on("*",function(b,c){a.trigger(b,c)})},e.prototype._registerEvents=function(){var a=this;this.on("open",function(){a.$container.addClass("select2-container--open")}),this.on("close",function(){a.$container.removeClass("select2-container--open")}),this.on("enable",function(){a.$container.removeClass("select2-container--disabled")}),this.on("disable",function(){a.$container.addClass("select2-container--disabled")}),this.on("blur",function(){a.$container.removeClass("select2-container--focus")}),this.on("query",function(b){a.isOpen()||a.trigger("open",{}),this.dataAdapter.query(b,function(c){a.trigger("results:all",{data:c,query:b})})}),this.on("query:append",function(b){this.dataAdapter.query(b,function(c){a.trigger("results:append",{data:c,query:b})})}),this.on("keypress",function(b){var c=b.which;a.isOpen()?c===d.ESC||c===d.TAB||c===d.UP&&b.altKey?(a.close(),b.preventDefault()):c===d.ENTER?(a.trigger("results:select",{}),b.preventDefault()):c===d.SPACE&&b.ctrlKey?(a.trigger("results:toggle",{}),b.preventDefault()):c===d.UP?(a.trigger("results:previous",{}),b.preventDefault()):c===d.DOWN&&(a.trigger("results:next",{}),b.preventDefault()):(c===d.ENTER||c===d.SPACE||c===d.DOWN&&b.altKey)&&(a.open(),b.preventDefault())})},e.prototype._syncAttributes=function(){this.options.set("disabled",this.$element.prop("disabled")),this.options.get("disabled")?(this.isOpen()&&this.close(),this.trigger("disable",{})):this.trigger("enable",{})},e.prototype._syncSubtree=function(a,b){var c=!1,d=this;if(!a||!a.target||"OPTION"===a.target.nodeName||"OPTGROUP"===a.target.nodeName){if(b)if(b.addedNodes&&b.addedNodes.length>0)for(var e=0;e<b.addedNodes.length;e++){var f=b.addedNodes[e];f.selected&&(c=!0)}else b.removedNodes&&b.removedNodes.length>0&&(c=!0);else c=!0;c&&this.dataAdapter.current(function(a){d.trigger("selection:update",{data:a})})}},e.prototype.trigger=function(a,b){var c=e.__super__.trigger,d={open:"opening",close:"closing",select:"selecting",unselect:"unselecting",clear:"clearing"};if(void 0===b&&(b={}),a in d){var f=d[a],g={prevented:!1,name:a,args:b};if(c.call(this,f,g),g.prevented)return void(b.prevented=!0)}c.call(this,a,b)},e.prototype.toggleDropdown=function(){this.options.get("disabled")||(this.isOpen()?this.close():this.open())},e.prototype.open=function(){this.isOpen()||this.trigger("query",{})},e.prototype.close=function(){this.isOpen()&&this.trigger("close",{})},e.prototype.isOpen=function(){return this.$container.hasClass("select2-container--open")},e.prototype.hasFocus=function(){return this.$container.hasClass("select2-container--focus")},e.prototype.focus=function(a){this.hasFocus()||(this.$container.addClass("select2-container--focus"),this.trigger("focus",{}))},e.prototype.enable=function(a){this.options.get("debug")&&window.console&&console.warn&&console.warn('Select2: The `select2("enable")` method has been deprecated and will be removed in later Select2 versions. Use $element.prop("disabled") instead.'),null!=a&&0!==a.length||(a=[!0]);var b=!a[0];this.$element.prop("disabled",b)},e.prototype.data=function(){this.options.get("debug")&&arguments.length>0&&window.console&&console.warn&&console.warn('Select2: Data can no longer be set using `select2("data")`. You should consider setting the value instead using `$element.val()`.');var a=[];return this.dataAdapter.current(function(b){a=b}),a},e.prototype.val=function(b){if(this.options.get("debug")&&window.console&&console.warn&&console.warn('Select2: The `select2("val")` method has been deprecated and will be removed in later Select2 versions. Use $element.val() instead.'),null==b||0===b.length)return this.$element.val();var c=b[0];a.isArray(c)&&(c=a.map(c,function(a){return a.toString()})),this.$element.val(c).trigger("change")},e.prototype.destroy=function(){this.$container.remove(),this.$element[0].detachEvent&&this.$element[0].detachEvent("onpropertychange",this._syncA),null!=this._observer?(this._observer.disconnect(),this._observer=null):this.$element[0].removeEventListener&&(this.$element[0].removeEventListener("DOMAttrModified",this._syncA,!1),this.$element[0].removeEventListener("DOMNodeInserted",this._syncS,!1),this.$element[0].removeEventListener("DOMNodeRemoved",this._syncS,!1)),this._syncA=null,this._syncS=null,this.$element.off(".select2"),this.$element.attr("tabindex",c.GetData(this.$element[0],"old-tabindex")),this.$element.removeClass("select2-hidden-accessible"),this.$element.attr("aria-hidden","false"),c.RemoveData(this.$element[0]),this.dataAdapter.destroy(),this.selection.destroy(),this.dropdown.destroy(),this.results.destroy(),this.dataAdapter=null,this.selection=null,this.dropdown=null,this.results=null},e.prototype.render=function(){var b=a('<span class="select2 select2-container"><span class="selection"></span><span class="dropdown-wrapper" aria-hidden="true"></span></span>');return b.attr("dir",this.options.get("dir")),this.$container=b,this.$container.addClass("select2-container--"+this.options.get("theme")),c.StoreData(b[0],"element",this.$element),b},e}),b.define("jquery-mousewheel",["jquery"],function(a){return a}),b.define("jquery.select2",["jquery","jquery-mousewheel","./select2/core","./select2/defaults","./select2/utils"],function(a,b,c,d,e){if(null==a.fn.select2){var f=["open","close","destroy"];a.fn.select2=function(b){if("object"==typeof(b=b||{}))return this.each(function(){var d=a.extend(!0,{},b);new c(a(this),d)}),this;if("string"==typeof b){var d,g=Array.prototype.slice.call(arguments,1);return this.each(function(){var a=e.GetData(this,"select2");null==a&&window.console&&console.error&&console.error("The select2('"+b+"') method was called on an element that is not using Select2."),d=a[b].apply(a,g)}),a.inArray(b,f)>-1?this:d}throw new Error("Invalid arguments for Select2: "+b)}}return null==a.fn.select2.defaults&&(a.fn.select2.defaults=d),c}),{define:b.define,require:b.require}}(),c=b.require("jquery.select2");return a.fn.select2.amd=b,c});;
/*! Responsive v4.1.4 | MIT License | responsivebp.com */
!function(t,i,e){"use strict";t.pseudoUnique=function(t){var i=t||8,e="",n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",a=n.length;i>a&&(i=a);for(var o=0;o<i;o+=1)e+=n.charAt(Math.floor(Math.random()*a));return e},t.support.rtl=function(){return!!t("html[dir=rtl]").length}(),t.support.currentGrid=function(){return function(){var i=t("<div/>").addClass("grid-state-indicator").prependTo("body"),e=["xxs","xs","s","m","l"],n=parseInt(i.width(),10);return i.remove(),{grid:e[n],index:n,range:e}}}(),t.support.scrollbarWidth=function(){return function(){var n=0;if(e.body.clientWidth<i.innerWidth){var a=t("<div/>").addClass("scrollbar-measure").prependTo("body");n=a[0].offsetWidth-a[0].clientWidth,a.remove()}return n}}(),t.toggleBodyLock=function(){var i,e=t("html"),n=t("body");if(void 0!==e.attr("data-lock"))return i=n.data("bodyPad"),n.css("padding-right",i||"").removeData("bodyPad"),void e.removeAttr("data-lock").trigger(t.Event("unlock.r.bodylock"));i=parseInt(n.css("padding-right")||0);var a=t.support.scrollbarWidth();a&&(n.css("padding-right",i+a),i&&n.data("bodyPad",i)),e.attr("data-lock","").trigger(t.Event("lock.r.bodylock",{padding:i+a}))},t.support.transition=function(){return function(){for(var t=e.createElement("div"),i={transition:"transitionend",WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend"},n=Object.keys(i),a=n.length,o=0;o<a;o++)if(void 0!==t.style[n[o]])return{end:i[n[o]]};return null}()}(),t.fn.redraw=function(){var t;return this.each(function(){t=this.offsetWidth})},function(){var e=function(t){var i=/\d+(.\d+)?/;return 1e3*(i.test(t.css("transition-duration"))?t.css("transition-duration").match(i)[0]:0)};t.fn.ensureTransitionEnd=function(n){if(!t.support.transition)return this;var a=!1,o=t(this),s=function(){a||o.trigger(t.support.transition.end)};return n||(n=e(o)),o.one(t.support.transition.end,function(){a=!0}),i.setTimeout(s,n),this},t.fn.onTransitionEnd=function(n){var a=t.support.transition;return this.each(function(){if(t.isFunction(n)){var o=t(this),s=e(o),r=s/10,d=new Date,h=arguments;o.redraw(),a?o.one(a.end,function(){if((new Date).getMilliseconds()-d.getMilliseconds()<=r)return void i.setTimeout(function(){n.apply(this,h)}.bind(this),s);n.apply(this,h)}):n.apply(this,h)}})}}(),t.support.touchEvents=function(){return"ontouchstart"in i||i.DocumentTouch&&e instanceof i.DocumentTouch}(),t.support.pointerEvents=function(){return i.PointerEvent||i.MSPointerEvent}(),function(){var i=t.support.touchEvents,e=t.support.pointerEvents,n=["pointerdown","MSPointerDown"],a=["pointermove","MSPointerMove"],o=["pointerup","pointerout","pointercancel","pointerleave","MSPointerUp","MSPointerOut","MSPointerCancel","MSPointerLeave"],s=["touchend","touchleave","touchcancel"],r=["mouseup","mouseleave"],d=function(t){var d,h,l;return i?(d="touchstart"+t,h="touchmove"+t,l=s.join(t+" ")+t):e?(d=n.join(t+" ")+t,h=a.join(t+" ")+t,l=o.join(t+" ")+t):(d="mousedown"+t,h="mousemove"+t,l=r.join(t+" ")+t),{start:d,move:h,end:l}},h=function(i,n){var a=n.namespace?"."+n.namespace:"",o=d(a),s=n.data&&n.data.touchAction||"none",r=n.data&&n.data.sensitivity||5;return e&&i.css({"-ms-touch-action":""+s,"touch-action":""+s}),i.each(function(){var i=t(this),e={},n={},a=function(a){var o,d="mousemove"===a.type,h="touchmove"!==a.type&&!d,l=a.originalEvent;if(!(d&&1!==a.which||l.touches&&l.touches.length>1||a.scale&&1!==a.scale)){var c,u=(d?l.pageX:h?l.clientX:l.touches[0].pageX)-e.x,p=(d?l.pageY:h?l.clientY:l.touches[0].pageY)-e.y,f=Math.abs(parseFloat(u/i.width()*100))||100,g=Math.abs(parseFloat(p/i.height()*100))||100;switch(s){case"pan-x":Math.abs(p)>Math.abs(u)&&a.preventDefault(),c=Math.abs(p)>Math.abs(u)&&Math.abs(p)>r&&g<100;break;case"pan-y":Math.abs(u)>Math.abs(p)&&a.preventDefault(),c=Math.abs(u)>Math.abs(p)&&Math.abs(u)>r&&f<100;break;default:a.preventDefault(),c=Math.abs(p)>r||Math.abs(u)>r&&f<100&&g<100}a.stopPropagation(),c&&(o=t.Event("swipemove",{delta:{x:u,y:p}}),i.trigger(o),o.isDefaultPrevented()||(n={x:u,y:p}))}},d=function(){var a,s=+new Date-e.time;if(Math.abs(n.x)>1||Math.abs(n.y)>1){var r=n.x<0?"left":"right",d=n.y<0?"up":"down",h=Math.abs(n.x)>Math.abs(n.y)?r:d;a=t.Event("swipeend",{delta:n,direction:h,duration:s}),i.trigger(a)}i.off(o.move).off(o.end)};i.off(o.start).on(o.start,function(s){var r="mousedown"===s.type,h="touchstart"!==s.type&&!r,l=s.originalEvent;(h||r)&&t(s.target).is("img")&&s.preventDefault(),s.stopPropagation(),e={x:r?l.pageX:h?l.clientX:l.touches[0].pageX,y:r?l.pageY:h?l.clientY:l.touches[0].pageY,time:+new Date};var c=t.Event("swipestart",{start:e});i.trigger(c),c.isDefaultPrevented()||(n={x:0,y:0},i.on(o.move,a).on(o.end,d))})})},l=function(i,e){var n=e.namespace?"."+e.namespace:"",a=d(n);return i.each(function(){t(this).css({"-ms-touch-action":"","touch-action":""}).off(a.start).off(a.move).off(a.end)})};t.event.special.swipe={add:function(i){h(t(this),i)},remove:function(i){l(t(this),i)}}}(),t.extend(t.expr[":"],{attrStart:function(i,e,n){var a=!1;return t.each(i.attributes,function(){return 0!==this.name.indexOf(n[3])||(a=!0,!1)}),a}}),t.getDataOptions=function(i,e){var n={};return t.each(i.data(),function(t,i){if(0===t.indexOf(e)&&t.length>e.length){var a=e.length;n[t.charAt(a).toLowerCase()+t.substring(a+1)]=i}}),Object.keys(n).length?n:i.data()},t.debounce=function(t,e,n){var a;return function(){var o=this,s=arguments;i.clearTimeout(a),a=i.setTimeout(function(){a=null,n||t.apply(o,s)},e),n&&!a&&t.apply(o,s)}},function(i){var n=t.Event("RBPchanged"),a=t(e);t.fn.html=function(){var t=i.apply(this,arguments);return arguments.length&&a.trigger(n),t}}(t.fn.html)}(jQuery,window,document),function(t,i,e,n){"use strict";if(!i.RESPONSIVE_AUTOSIZE){var a=["RBPchanged"+e+n,"shown.r.modal"+n].join(" "),o=["resize"+e,"orientationchange"+e].join(" ");!function(i){t.fn.val=function(){var e=i.apply(this,arguments);return this.data("r.autosize")&&arguments.length&&this.trigger(t.Event("input")),e}}(t.fn.val);var s=function(e,n){this.$element=t(e),this.element=e,this.options=t.extend({},this.defaults,n),this.sizing=null,this.difference=0,this.height=this.$element.height(),this.init(),this.$element.on(["input","keyup"].join(" "),t.debounce(t.proxy(this.size,this),100)),t(i).on(o,t.debounce(t.proxy(this.size,this),100))};s.prototype.init=function(){var t=this.$element.outerHeight();this.difference=parseFloat(this.$element.css("paddingBottom"))+parseFloat(this.$element.css("paddingTop")),this.element.scrollHeight+this.difference<=t&&(this.difference=0),this.element.value.replace(/\s/g,"").length>0&&this.$element.height(this.element.scrollHeight)},s.prototype.size=function(){var i=this,n=this.$element,a=this.element,o=t.Event("size"+e);if(!this.sizing){n.height("auto");var s=a.scrollHeight-this.difference,r=this.height!==s;if(n.height(this.height),r&&n.trigger(o),!this.sizing&&!o.isDefaultPrevented()){if(this.sizing=!0,n.height(s),r)return void n.onTransitionEnd(function(){i.sizing=!1,i.height=s,n.trigger(t.Event("sized"+e))});this.sizing=!1}}};var r=t.fn.autoSize;t.fn.autoSize=function(i){return this.each(function(){var e=t(this),n=e.data("r.autosize"),a="object"==typeof i?t.extend({},i):null;n||e.data("r.autosize",n=new s(this,a)),"size"===i&&n.size()})},t.fn.autoSize.Constructor=s,t.fn.autoSize.noConflict=function(){return t.fn.autoSize=r,this};var d=function(){t("textarea[data-autosize]").each(function(){var i=t(this);i.data("r.autosizeLoaded")||(i.data("r.autosizeLoaded",!0),i.addClass("autosize").autoSize(t.getDataOptions(i,"autosize")))})},h=t.debounce(d,500);t(document).on(["RBPinit"+e+n,a].join(" "),function(t){"RBPinit"===t.type?d():h()}).ready(function(){t(this).trigger("RBPinit"+e+n)}),i.RESPONSIVE_AUTOSIZE=!0}}(jQuery,window,".r.autosize",".data-api"),function(t,i,e,n){"use strict";if(!i.RESPONSIVE_CAROUSEL){var a=t.support.transition,o=t.support.rtl,s=["RBPchanged"+e+n,"shown.r.modal"+n].join(" "),r={SPACE:32,ENTER:13,LEFT:37,RIGHT:39},d=function(e,n){this.$element=t(e),this.defaults={interval:0,mode:"slide",pause:"hover",wrap:!0,keyboard:!0,touch:!0,lazyImages:!0,lazyOnDemand:!0,nextTrigger:null,nextHint:"Next ("+(o?"Left":"Right")+" Arrow)",previousTrigger:null,previousHint:"Previous ("+(o?"Right":"Left")+" Arrow)",indicators:null},this.options=t.extend({},this.defaults,n),this.paused=null,this.interval=null,this.sliding=null,this.$items=null,this.keyboardTriggered=null,this.translationDuration=null,this.$nextTrigger=this.options.nextTrigger?t(this.options.nextTrigger):this.$element.children("button.forward"),this.$previousTrigger=this.options.previousTrigger?t(this.options.previousTrigger):this.$element.children("button:not(.forward)"),this.$indicators=this.options.indicators?t(this.options.indicators):this.$element.find("> ol > li"),this.id=this.$element.attr("id")||"carousel-"+t.pseudoUnique();var a=this,s=this.activeindex();this.options.wrap||0===s&&this.$previousTrigger.attr({"aria-hidden":!0,hidden:!0}),1===this.$items.length&&(this.$previousTrigger.attr({"aria-hidden":!0,hidden:!0}),this.$nextTrigger.attr({"aria-hidden":!0,hidden:!0})),"fade"===this.options.mode&&this.$element.addClass("carousel-fade"),this.options.lazyImages&&!this.options.lazyOnDemand&&t(i).on("load",t.proxy(this.lazyimages),this),this.$element.attr({role:"listbox","aria-live":"polite",id:this.id}),this.$element.children("figure").each(function(i){var e=i===s;t(this).attr({role:"option","aria-selected":e,tabindex:e?0:-1})}),this.$nextTrigger.add(this.$previousTrigger).each(function(){var i=t(this).attr({tabindex:0,"aria-controls":a.id});i.is("button")?i.attr({type:"button"}):i.attr({role:"button"}),i.find(".visuallyhidden").length||t("<span/>").addClass("visuallyhidden").html(this===a.$nextTrigger.get(0)?a.options.nextHint:a.options.previousHint).appendTo(i)}),this.$indicators.attr({role:"button","aria-controls":a.id}).eq(s).addClass("active"),"hover"===this.options.pause&&(t.support.touchEvents||t.support.pointerEvents||this.$element.on("mouseenter",t.proxy(this.pause,this)).on("mouseleave",t.proxy(this.cycle,this))),this.options.touch&&this.$element.on("swipe.carousel",{touchAction:"pan-y"},function(){return!0}).on("swipemove.carousel",t.proxy(this.swipemove,this)).on("swipeend.carousel",t.proxy(this.swipeend,this)),this.options.keyboard&&this.$element.on("keydown",t.proxy(this.keydown,this)),t(document).on(this.options.keyboard?["click","keydown"].join(" "):"click","[aria-controls="+this.id+"]",t.proxy(this.click,this))};d.prototype.activeindex=function(){var t=this.$element.find(".carousel-active");return this.$items=t.parent().children("figure"),this.$items.index(t)},d.prototype.cycle=function(e){return e||(this.paused=!1),this.interval&&i.clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=i.setInterval(t.proxy(this.next,this),this.options.interval)),this},d.prototype.to=function(i){var e=this.activeindex(),n=this;return!(i>this.$items.length-1||i<0)&&(this.sliding?this.$element.one("slid"+e,function(){n.to(i)}):e===i?this.pause().cycle():this.slide(i>e?"next":"prev",t(this.$items[i])))},d.prototype.pause=function(e){return e||(this.paused=!0),this.$element.find(".next, .prev").length&&t.support.transition&&(this.$element.trigger(t.support.transition.end),this.cycle(!0)),this.interval=i.clearInterval(this.interval),this},d.prototype.next=function(){return!this.sliding&&this.slide("next")},d.prototype.prev=function(){return!this.sliding&&this.slide("prev")},d.prototype.slide=function(i,n){var a,o,s=this.$element.children("figure.carousel-active"),r=n||s[i]("figure"),d=this.interval,h="next"===i,l=h?"left":"right",c=h?"first":"last",u=this;if(d&&this.pause(),!r.length){if(!this.options.wrap)return!1;r=this.$element.children("figure")[c]()}if(r.hasClass("carousel-active"))return this.sliding=!1;if(a=t.Event("slide"+e,{relatedTarget:r[0],direction:l}),this.$element.trigger(a),a.isDefaultPrevented())return!1;this.options.lazyImages&&this.options.lazyOnDemand&&this.lazyimages.call(r),this.sliding=!0,d&&this.pause(),this.$element.one("slid"+e,function(){if(!u.options.wrap){var t=u.activeindex();u.$items&&t===u.$items.length-1?(u.$nextTrigger.attr({"aria-hidden":!0,hidden:!0}),u.$previousTrigger.removeAttr("aria-hidden").removeAttr("hidden"),u.keyboardTriggered&&(u.$previousTrigger.focus(),u.keyboardTriggered=!1)):u.$items&&0===t?(u.$previousTrigger.attr({"aria-hidden":!0,hidden:!0}),u.$nextTrigger.show().removeAttr("aria-hidden").removeAttr("hidden"),u.keyboardTriggered&&(u.$nextTrigger.focus(),u.keyboardTriggered=!1)):(u.$nextTrigger.removeAttr("aria-hidden").removeAttr("hidden"),u.$previousTrigger.removeAttr("aria-hidden").removeAttr("hidden"),u.keyboardTriggered=!1)}u.$indicators.removeClass("active").eq(u.activeindex()).addClass("active")});var p=function(){u.$items&&u.$items.removeClass("swiping").css({"transition-duration":""}),s.removeClass(["carousel-active",l].join(" ")).attr({"aria-selected":!1,tabIndex:-1}),r.removeClass([i,l].join(" ")).addClass("carousel-active").attr({"aria-selected":!0,tabIndex:0}),u.sliding=!1,o=t.Event("slid"+e,{relatedTarget:r[0],direction:l}),u.$element.trigger(o)};return r.addClass(i).redraw(),s.addClass(l),r.addClass(l),this.$items&&this.$items.each(function(){t(this).removeClass("swipe swipe-next").css({left:"",right:"",opacity:""})}),s.onTransitionEnd(p).ensureTransitionEnd(),d&&this.cycle(),this},d.prototype.keydown=function(t){if(!/input|textarea/i.test(t.target.tagName)){var i=t&&t.which;if(i===r.LEFT||i===r.RIGHT)switch(this.keyboardTriggered=!0,t.preventDefault(),t.stopPropagation(),i){case r.LEFT:o?(this.next(),this.$nextTrigger.focus()):(this.prev(),this.$previousTrigger.focus());break;case r.RIGHT:o?(this.prev(),this.$previousTrigger.focus()):(this.next(),this.$nextTrigger.focus())}}},d.prototype.click=function(i){if(i){var e=i.which;if(e&&1!==e){if(e!==r.SPACE&&e!==r.ENTER)return;this.keyboardTriggered=!0}i.preventDefault(),i.stopPropagation();var n=t(i.target);n.hasClass("forward")?this.next():n.is("button")?this.prev():this.to(n.index())}},d.prototype.swipemove=function(t){if(!this.sliding){this.pause();var i=t.delta.x<0,e=i?o?"prev":"next":o?"next":"prev",n=i?o?"last":"first":o?"first":"last",a=this.activeindex(),s=this.$items.eq(a),r=s[e]("figure");if(1!==this.$items.length){if(!r.length){if(!this.options.wrap)return;r=this.$element.children("figure")[n]()}if(this.$items.not(s).not(r).removeClass("swipe swiping swipe-next").css({left:"",right:"",opacity:""}),!r.hasClass("carousel-active")){this.options.lazyImages&&this.options.lazyOnDemand&&this.lazyimages.call(r);var d=s.width(),h=parseFloat(t.delta.x/d*100),l=i?100:-100;o&&(h*=-1),this.$element.addClass("no-transition"),"slide"===this.options.mode?o?(s.addClass("swiping").css({right:h+"%"}),r.addClass("swipe swipe-next").css({right:h-l+"%"})):(s.addClass("swiping").css({left:h+"%"}),r.addClass("swipe swipe-next").css({left:h+l+"%"})):(s.addClass("swipe").css({opacity:1-Math.abs(h/100)}),r.addClass("swipe swipe-next"))}}}},d.prototype.swipeend=function(i){if(!this.sliding&&this.$element.hasClass("no-transition")){var e=i.direction,n="next";if("right"===e&&(n="prev"),this.$element.removeClass("no-transition"),a){var o=this.activeindex(),s=this.$items.eq(o);this.translationDuration||(this.translationDuration=parseFloat(s.css("transition-duration")));var r=s.width(),d=Math.abs(i.delta.x)/r*100,h=i.duration/1e3*100/d,l=(100-d)/100*Math.min(this.translationDuration,h);this.$items.each(function(){t(this).css({"transition-duration":l+"s"})})}this.cycle(),this.slide(n,t(this.$items.filter(".swipe-next")))}},d.prototype.lazyimages=function(){this.data("lazyLoaded")||(this.find("img[data-src]").each(function(){0===this.src.length&&(this.src=this.getAttribute("data-src"))}),this.data("lazyLoaded",!0))};var h=t.fn.carousel;t.fn.carousel=function(i){return this.each(function(){var e=t(this),n=e.data("r.carousel"),a="object"==typeof i?i:null;n||e.data("r.carousel",n=new d(this,a)),"number"==typeof i?n.to(i):"string"==typeof i&&/(cycle|pause|next|prev)/.test(i)||(i=a&&a.slide)?n[i]():n.options.interval&&n.pause().cycle()})},t.fn.carousel.Constructor=d,t.fn.carousel.noConflict=function(){return t.fn.carousel=h,this};var l=function(){t(".carousel").each(function(){var i=t(this);i.data("r.carouselLoaded")||(i.data("r.carouselLoaded",!0),i.carousel(t.getDataOptions(i,"carousel")))})},c=t.debounce(l,500);t(document).on(["RBPinit"+e+n,s].join(" "),function(t){"RBPinit"===t.type?l():c()}).ready(function(){t(this).trigger("RBPinit"+e+n)}),i.RESPONSIVE_CAROUSEL=!0}}(jQuery,window,".r.carousel",".data-api"),function(t,i,e,n){"use strict";if(!i.RESPONSIVE_CONDITIONAL){var a=["RBPchanged"+e+n,"shown.r.modal"+n].join(" "),o=["resize"+e,"orientationchange"+e].join(" "),s=function(e,n){this.$element=t(e),this.defaults={xxs:null,xs:null,s:null,m:null,l:null,fallback:null,errorHint:"<p>An error has occured.</p>"},this.cache={},this.options=t.extend({},this.defaults,n),this.currentGrid=null,this.currentTarget=null,this.loading=null,t(i).on(o,t.debounce(t.proxy(this.resize,this),50)),this.resize()};s.prototype.resize=function(){var i=t.support.currentGrid(),n=i.grid,a=i.range;if(!this.options.fallback)for(var o in a)if(a.hasOwnProperty(o)){var s=a[o];this.options[s]||(this.options[s]="fallback",this.cache[s]=this.$element.html())}if(this.currentGrid!==n){this.currentGrid=n;var r=this,d=this.options[n]||this.options.fallback;if(d&&d!==this.currentTarget){this.currentTarget=d;var h=t.Event("load"+e);if(this.$element.trigger(h),this.loading||h.isDefaultPrevented())return;this.loading=!0,this.cache[this.currentGrid]?(this.$element.empty().html(this.cache[this.currentGrid]),this.loading=!1,this.$element.trigger(t.Event("loaded"+e,{relatedTarget:r.$element[0],loadTarget:d,grid:this.currentGrid}))):this.$element.empty().load(d,null,function(i,a){if("error"===a)return r.$element.trigger(t.Event("error"+e,{relatedTarget:r.$element[0],loadTarget:d,grid:r.currentGrid})),r.$element.html(r.options.errorHint),void(r.loading=!1);var o,s=d.indexOf(" ");s>=0&&(o=t.trim(d.slice(s))),r.cache[n]=o?t("<div>").append(t.parseHTML(i)).find(o).wrap("<div>").parent().html():i,r.loading=!1,r.$element.trigger(t.Event("loaded"+e,{relatedTarget:r.$element[0],loadTarget:d,grid:r.currentGrid}))})}}};var r=t.fn.conditional;t.fn.conditional=function(i){return this.each(function(){var e=t(this),n=e.data("r.conditional"),a="object"==typeof i?t.extend({},i):null;n||e.data("r.conditional",n=new s(this,a)),"resize"===i&&n.resize()})},t.fn.conditional.Constructor=s,t.fn.conditional.noConflict=function(){return t.fn.conditional=r,this};var d=function(){t(":attrStart(data-conditional)").each(function(){var i=t(this);i.data("r.conditionalLoaded")||(i.data("r.conditionalLoaded",!0),i.conditional(t.getDataOptions(i,"conditional")))})},h=t.debounce(d,500);t(document).on(["RBPinit"+e+n,a].join(" "),function(t){"RBPinit"===t.type?d():h()}).ready(function(){t(this).trigger("RBPinit"+e+n)}),i.RESPONSIVE_CONDITIONAL=!0}}(jQuery,window,".r.conditional",".data-api"),function(t,i,e,n){"use strict";if(!i.RESPONSIVE_DISMISS){var a=["RBPchanged"+e+n,"shown.r.modal"+n].join(" "),o=function(i,e){this.defaults={closeHint:"Click to close"},this.options=t.extend({},this.defaults,e),this.$element=t(i).attr({type:"button"}),this.$target=this.$element.closest(e.target),this.dismissing=null,this.$element.is("button")&&t(i).attr({type:"button"}),this.$target.hasClass("alert")&&this.$target.attr({role:"alert"}),this.$element.find(".visuallyhidden").length||t("<span/>").addClass("visuallyhidden").html(this.options.closeHint).appendTo(this.$element),this.$element.on("click",t.proxy(this.click,this))};o.prototype.close=function(){var i=t.Event("dismiss"+e),n=this.$target,a=this,o=function(){a.dismissing=!1,n.removeClass("fade-out").attr({"aria-hidden":!0,hidden:!0,tabindex:-1}),a.$element.trigger(t.Event("dismissed"+e))};this.$element.trigger(i),this.dismissing||i.isDefaultPrevented()||(this.dismissing=!0,n.addClass("fade-in fade-out").redraw().removeClass("fade-in"),this.$target.onTransitionEnd(o))},o.prototype.click=function(t){t.preventDefault(),this.close()};var s=t.fn.dismiss;t.fn.dismiss=function(i){return this.each(function(){var e=t(this),n=e.data("dismiss");n||e.data("dismiss",n=new o(this,i)),"close"===i&&n.close()})},t.fn.dismiss.Constructor=o,t.fn.dismiss.noConflict=function(){return t.fn.dismiss=s,this};var r=function(){t("button[data-dismiss-target]").each(function(){var i=t(this);i.data("r.dismissLoaded")||(i.data("r.dismissLoaded",!0),i.dismiss(t.getDataOptions(i,"dismiss")))})},d=t.debounce(r,500);t(document).on(["RBPinit"+e+n,a].join(" "),function(t){"RBPinit"===t.type?r():d()}).ready(function(){t(this).trigger("RBPinit"+e+n)}),i.RESPONSIVE_DISMISS=!0}}(jQuery,window,".r.dismiss",".data-api"),function(t,i,e,n){"use strict";if(!i.RESPONSIVE_DROPDOWN){var a=i.getComputedStyle&&t.support.transition,o=t.support.rtl,s=["RBPchanged"+e+n,"shown.r.modal"+n].join(" "),r={SPACE:32,LEFT:37,RIGHT:39},d=function(i,e){this.$element=t(i),this.$target=t(e.target),this.defaults={dimension:"height"},this.options=t.extend({},this.defaults,e),this.$parent=null,this.transitioning=null,this.endSize=null,this.options.parent&&(this.$parent=this.$target.closest(this.options.parent));var n=this.$element.attr("id")||"dropdown-"+t.pseudoUnique(),a=this.$target.attr("id")||"dropdown-"+t.pseudoUnique(),o=!this.$target.hasClass("collapse");this.$element.attr({id:n,role:"tab","aria-controls":a,"aria-selected":o,"aria-expanded":o,tabindex:0}),this.$parent&&(this.$parent.attr({role:"tablist","aria-multiselectable":"true"}),this.$element.attr({"data-dropdown-parent":this.options.parent})),this.$target.attr({id:a,role:"tabpanel","aria-labelledby":n,"aria-hidden":!o,hidden:!o,tabindex:o?0:-1}),this.$element.on("click",t.proxy(this.click,this)),this.$element.on("keydown",t.proxy(this.keydown,this))};d.prototype.show=function(){if(!this.transitioning&&!this.$target.hasClass("expand")){this.transitioning=!0;var n,o=this,s=this.options.dimension,r=[];this.$parent&&(r=this.$parent.find('[data-dropdown-parent="'+this.options.parent+'"]'),r=t.grep(r,function(i){var e=t(i).data("r.dropdown"),n=e&&e.$target;return n&&!n.hasClass("collapse")&&e.$parent&&e.$parent[0]===o.$parent[0]})),this.$target[s](0),a&&(this.$target[s]("auto").attr({"aria-hidden":!1,hidden:!1}),this.$target.find("[tabindex]:not(.collapse)").attr({"aria-hidden":!1,hidden:!1}),n=i.getComputedStyle(this.$target[0])[s],this.$target[s](0).redraw()),this.$target[s](n||""),this.transition("removeClass",t.Event("show"+e,{relatedTarget:this.options.target}),"shown"+e),r&&r.length&&t.each(r,function(){t(this).dropdown("hide")})}},d.prototype.hide=function(){if(!this.transitioning&&!this.$target.hasClass("collapse")){this.transitioning=!0;var n,o=this.options.dimension;a&&(n=i.getComputedStyle(this.$target[0])[o],this.$target[o](n).redraw()),this.$target.removeClass("expand"),this.$target[o](0),this.transition("addClass",t.Event("hide"+e,{relatedTarget:this.options.target}),"hidden"+e)}},d.prototype.toggle=function(){this.transitioning||this[this.$target.hasClass("collapse")?"show":"hide"]()},d.prototype.transition=function(i,e,n){var a=this,o="removeClass"===i,s=function(){var i=t.Event(n,{relatedTarget:a.options.target});a.$target.removeClass("trans")[a.options.dimension](""),a.$target.attr({"aria-hidden":!o,hidden:!o,tabindex:o?0:-1});var e=t("#"+a.$target.attr("aria-labelledby")).attr({"aria-selected":o,"aria-expanded":o});o&&e.focus(),a.$target.find("[tabindex]:not(.collapse)").attr({"aria-hidden":!o,hidden:!o,tabindex:o?0:-1}),a.transitioning=!1,a.$element.trigger(i)};this.$element.trigger(e),e.isDefaultPrevented()||(this.$target[i]("collapse"),this.$target["show"===e.type?"addClass":"removeClass"]("trans expand"),this.$target.onTransitionEnd(s))},d.prototype.click=function(t){t.preventDefault(),t.stopPropagation(),this.toggle()},d.prototype.keydown=function(i){if(!/input|textarea/i.test(i.target.tagName)){var e=i.which;if(e===r.SPACE||e===r.LEFT||e===r.RIGHT){i.preventDefault(),i.stopPropagation();var n=t(i.target);if(e===r.SPACE)return void this.toggle();var a=this.options.parent?n.closest("[role=tablist]"):n.closest(".accordion"),s=a.find('[data-dropdown-parent="'+this.options.parent+'"]'),d=s.index(s.filter(":focus")),h=s.length;e===r.LEFT?o?d+=1:d-=1:e===r.RIGHT&&(o?d-=1:d+=1),d===h&&(d=0),d<0&&(d=h-1);var l=t(s.eq(d)).data("r.dropdown");l&&l.show()}}};var h=t.fn.dropdown;t.fn.dropdown=function(i){return this.each(function(){var e=t(this),n=e.data("r.dropdown"),a="object"==typeof i?t.extend({},i):null;n||e.data("r.dropdown",n=new d(this,a)),"string"==typeof i&&/(show|hide|toggle)/.test(i)&&n[i]()})},t.fn.dropdown.Constructor=d,t.fn.dropdown.noConflict=function(){return t.fn.dropdown=h,this};var l=function(){t(":attrStart(data-dropdown)").each(function(){var i=t(this);i.data("r.dropdownLoaded")||(i.data("r.dropdownLoaded",!0),i.dropdown(t.getDataOptions(i,"dropdown")))})},c=t.debounce(l,500);t(document).on(["RBPinit"+e+n,s].join(" "),function(t){"RBPinit"===t.type?l():c()}).ready(function(){t(this).trigger("RBPinit"+e+n)}),i.RESPONSIVE_DROPDOWN=!0}}(jQuery,window,".r.dropdown",".data-api"),function(t,i,e,n){"use strict";if(!i.RESPONSIVE_MODAL){var a=t(i),o=t("body"),s=t("<div/>").attr({role:"document"}).addClass("modal-overlay modal-loader fade-out"),r=t("<div/>").addClass("modal fade-out").appendTo(s),d=t("<div/>").addClass("modal-header fade-out"),h=t("<div/>").addClass("modal-footer fade-out"),l=t("<button/>").attr({type:"button"}).addClass("modal-close fade-out"),c=t("<button/>").attr({type:"button"}).addClass("modal-direction prev fade-out"),u=t("<button/>").attr({type:"button"}).addClass("modal-direction next fade-out"),p=t("<div/>").addClass("modal-placeholder"),f=["resize"+e,"orientationchange"+e].join(" "),g="click"+e,v=t.support.rtl,m=t.support.currentGrid(),y={ESCAPE:27,LEFT:37,RIGHT:39},b=0,$=0===i.location.protocol.indexOf("http")?i.location.protocol:"http:",w=new RegExp("//"+i.location.host+"($|/)"),x=/(^data:image\/.*,)|(\.(jp(e|g|eg)|gif|png|bmp|ti(ff|f)|webp|svg)((\?|#).*)?$)/i,C=/^#.*$/,T=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,E=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,P=function(e,n){this.$element=t(e),this.defaults={modal:null,external:!1,group:null,image:!1,immediate:!1,iframe:!1,iframeScroll:!0,keyboard:!0,touch:!0,next:">",nextHint:"Next ("+(v?"Left":"Right")+" Arrow)",previous:"<",previousHint:"Previous ("+(v?"Right":"Left")+" Arrow)",closeHint:"Close (Esc)",errorHint:"<p>An error has occured.</p>",mobileTarget:null,mobileViewportWidth:"xs",fitViewport:!0},this.options=t.extend({},this.defaults,n),this.title=null,this.description=null,this.isShown=null,this.$group=null,this.options.group&&(this.$group=t(this.options.group)),0===o.length&&(o=t("body")),this.$element.on(g,this.click.bind(this));var a=t.debounce(this.resize.bind(this),15);t(i).off(f).on(f,a),this.options.immediate&&this.show()};P.prototype.click=function(t){t.preventDefault();var e=r.data("currentModal");if(e&&e[0]!==this.$element[0]){var n=function(){i.setTimeout(function(){this.show(!0)}.bind(this),150)}.bind(this);return e.data("r.modal").toggleModal(!0,!0),void r.onTransitionEnd(n)}this.show()},P.prototype.show=function(n){if(!this.isShown){var o=t.Event("show"+e);if(this.$element.trigger(o),!o.isDefaultPrevented()){if(this.isShown=!0,this.options.mobileTarget){var s=this.options.mobileViewportWidth;if("number"==typeof s&&s>=a.width())return void(i.location.href=this.options.mobileTarget);if("string"==typeof s){var r=t.inArray(s,m.range);if(m.index<=r&&r>-1)return void(i.location.href=this.options.mobileTarget)}}if(!n)return void this.overlay();this.toggleModal()}}},P.prototype.hide=function(){this.toggleModal(!0)},P.prototype.overlay=function(){if(t(".modal-overlay").length||o.append(s.removeClass("fade-in")),s.hasClass("fade-in")){var i=function(){r.removeData("currentModal").removeAttr("tabindex"),t.toggleBodyLock(),s.attr("hidden"," "),a.scrollTop(b)}.bind(this);return void s.removeClass("fade-in").onTransitionEnd(i)}void 0===t("html").attr("data-lock")&&(b=a.scrollTop(),t.toggleBodyLock()),s.removeAttr("hidden").redraw().addClass("fade-in").onTransitionEnd(function(){this.toggleModal()}.bind(this))},P.prototype.toggleModal=function(n,a){var p;if(!n)return p=function(){var i=r.find("[autofocus]");o.attr({tabindex:-1}),r.data("currentModal",this.$element).attr({tabindex:0}),i.length?i.focus():r.focus(),t(document).off("focusin"+e).on("focusin"+e,this.focus.bind(this)),this.options.keyboard&&t(document).off("keydown"+e).on("keydown"+e,this.keydown.bind(this)),this.options.group&&this.options.touch&&r.off("swipe.modal").on("swipe.modal",function(){return!0}).off("swipeend.modal").on("swipeend.modal",this.swipeend.bind(this)),s.off(g).on(g,this.overlayclick.bind(this)),this.$element.trigger(t.Event("shown"+e))}.bind(this),this.create(),void r.onTransitionEnd(p).off(g).on(g,this.modalclick.bind(this));if(this.isShown){var f=t.Event("hide"+e);this.$element.trigger(f),f.isDefaultPrevented()||(this.isShown=!1,s.removeClass("modal-loader"),t.each([d,h,l,u,c,r],function(){this.removeClass("fade-in")}),p=function(){return this.$sibling&&this.$sibling.data("r.modal")?(this.destroy(!0),this.$element.trigger(t.Event("hidden"+e)),void i.setTimeout(function(){this.$sibling.data("r.modal").show(!0),this.$sibling=null}.bind(this),150)):a?(this.destroy(!0),void this.$element.trigger(t.Event("hidden"+e))):(this.destroy(),void this.$element.trigger(t.Event("hidden"+e)))}.bind(this),r.onTransitionEnd(p))}},P.prototype.create=function(){s.addClass("modal-loader");var i=function(t){var i=T.exec(t)||T.exec($+t);return void 0!==i&&!C.test(t)&&(!(!i||!i[2]||E.test(i[1]))&&!w.test(i[2]))},n=function(){this.resize(),t.each([d,h,l,u,c,r],function(){this.addClass("fade-in")}),r.redraw(),s.removeClass("modal-loader")}.bind(this),a=this.options.title,o=this.options.description,f=this.options.modal,g=this.options.target,v=!C.test(this.options.target),m=i(g),y=!v&&!m,b=this.$group,P=this.options.next+'<span class="visuallyhidden">'+this.options.nextHint+"</span>",S=this.options.previous+'<span class="visuallyhidden">'+this.options.previousHint+"</span>",k=this.options.iframeScroll,R=this.options.image||x.test(g),D=!!(this.options.iframe||v&&m)&&!R,A=t("<div/>").addClass(k?"media media-scroll":"media"),O=t("<div/>").addClass("modal-content");if(b){b.filter(function(){return t(this).data("r.modal")}).length&&(u.html(P).prependTo(r),c.html(S).prependTo(r))}if(a||!f){if(a){var z="modal-label-"+t.pseudoUnique();d.html('<div class="container"><h2 id="'+z+'">'+a+"</h2></div>").appendTo(s.attr({"aria-labelledby":z}))}f||l.html('x <span class="visuallyhidden">'+this.options.closeHint+"</span>").appendTo(s)}if(o&&h.html('<div class="container">'+o+"</div>").appendTo(s),y){var I=t(g);this.isLocalHidden=I.is(":hidden"),r.addClass(this.options.fitViewport?"container":""),p.detach().insertAfter(I),I.detach().appendTo(O).removeClass("hidden").attr({"aria-hidden":!1,hidden:!1}),O.appendTo(r),n()}else if(D){r.addClass("modal-iframe");var L=i(g)&&0!==g.indexOf("http")?$+g:g;t("<iframe/>").attr({scrolling:k?"yes":"no",allowTransparency:!0,frameborder:0,hspace:0,vspace:0,webkitallowfullscreen:"",mozallowfullscreen:"",allowfullscreen:""}).one("load error",function(){n()}).appendTo(A).attr("src",L);var j=function(t){var i={youtube:/youtu(be\.com|be\.googleapis\.com|\.be)/i,vimeo:/vimeo/i,vine:/vine/i,instagram:/instagram|instagr\.am/i,getty:/embed\.gettyimages\.com/i};for(var e in i)if(i.hasOwnProperty(e)&&i[e].test(t))return[e,"scaled"].join(" ");return!1}(g)||"";j||r.addClass("iframe-full"),A.addClass(j).appendTo(r)}else R?(r.addClass("modal-image"),t("<img/>").one("load error",function(){n()}).appendTo(r).attr("src",g)):(r.addClass("modal-ajax"),r.addClass(this.options.fitViewport?"container":""),O.load(g,null,function(i,a){
"error"===a&&(this.$element.trigger(t.Event("error"+e,{relatedTarget:O[0]})),O.html(this.options.errorHint)),O.appendTo(r),n()}.bind(this)))},P.prototype.destroy=function(e){u.detach(),c.detach(),d.empty().detach(),h.empty().detach(),l.detach(),s.removeAttr("aria-labelledby"),this.options.external||r.is(".modal-iframe, .modal-ajax, .modal-image")||(t(this.options.target).addClass(this.isLocalHidden?"hidden":"").attr({"aria-hidden":!!this.isLocalHidden,hidden:!!this.isLocalHidden}).detach().insertAfter(p),p.detach().insertAfter(s)),r.find("iframe").attr("src",""),i.setTimeout(function(){r.removeClass("modal-iframe iframe-full modal-ajax modal-image container").css({"max-height":"","max-width":""}).empty()}.bind(this),100),e||this.overlay()},P.prototype.overlayclick=function(i){if(!this.options.modal){var e=l[0],n=i.target;if(n!==r[0]&&!t.contains(r[0],n))return n===e?void this.hide():void((n===s[0]||t.contains(s[0],n))&&this.hide())}},P.prototype.modalclick=function(t){var i=u[0],e=c[0],n=t.target;if(n===i||n===e)return t.preventDefault(),t.stopPropagation(),void this[n===i?"next":"prev"]();this.options.modal&&n===r.find(this.options.modal)[0]&&(t.preventDefault(),t.stopPropagation(),this.hide())},P.prototype.focus=function(i){if(i.target!==s[0]&&!t.contains(s[0],i.target)){var e=r.find("a, area, button, input, object, select, textarea, [tabindex]").first();return e.length?e.focus():r.focus(),!1}return!0},P.prototype.keydown=function(t){if(!this.options.modal){if(t.which===y.ESCAPE)return void this.hide();if(this.options.group){if(/input|textarea/i.test(t.target.tagName))return;t.which===y.LEFT&&(v?this.next():this.prev()),t.which===y.RIGHT&&(v?this.prev():this.next())}}},P.prototype.swipeend=function(t){if(v)return void this["right"===t.direction?"prev":"next"]();this["right"===t.direction?"next":"prev"]()},P.prototype.resize=function(){var i=a.height(),e=d.length&&d.height()||0,n=l.length&&l.outerHeight()||0,o=n>e?n:e,s=h.length&&h.height()||0,c=.95*(i-(o+s));if(t(".modal-overlay").css({"padding-top":o,"padding-bottom":s}),r.hasClass("modal-image"))r.children("img").css("max-height",c);else if(r.hasClass("modal-iframe")){var u=r.find(".media > iframe"),p=u.width(),f=u.height(),g=p/f,v=c*g;u.parent().hasClass("scaled")&&r.css({"max-height":c,"max-width":v})}else{var y=r.children(".modal-content");t.each([r,y],function(){this.css({"max-height":c})})}m=t.support.currentGrid()},P.prototype.direction=function(i){if(this.isShown&&this.options.group){var e=this.$group.index(this.$element),n=this.$group.length,a="next"===i?e+1:e-1;"next"===i?(a>=n||a<0)&&(a=0):(a>=n&&(a=0),a<0&&(a=n-1)),this.$sibling=t(this.$group[a]),this.hide()}},P.prototype.next=function(){this.direction("next")},P.prototype.prev=function(){this.direction("prev")};var S=t.fn.modal;t.fn.modal=function(i){return this.each(function(){var e=t(this),n=e.data("r.modal"),a="object"==typeof i?t.extend({},i):{};a.target||(a.target=e.attr("href")),n||e.data("r.modal",n=new P(this,a)),"string"==typeof i&&/(show|hide|next|prev)/.test(i)&&n[i]()})},t.fn.modal.Constructor=P,t.fn.modal.noConflict=function(){return t.fn.modal=S,this};var k=function(){t(":attrStart(data-modal)").each(function(){var i=t(this);i.data("r.modalLoaded")||(i.data("r.modalLoaded",!0),i.modal(t.getDataOptions(i,"modal")))})},R=t.debounce(k,500);t(document).on(["RBPinit"+e+n,"RBPchanged"+e+n,"shown"+e].join(" "),function(t){"RBPinit"===t.type?k():R()}).ready(function(){t(this).trigger("RBPinit"+e+n)}),i.RESPONSIVE_MODAL=!0}}(jQuery,window,".r.modal",".data-api"),function(t,i,e,n){"use strict";if(!i.RESPONSIVE_NAVIGATION){var a=t(i),o=["RBPchanged"+e+n,"shown.r.modal"+n].join(" "),s={SPACE:32,ESCAPE:27},r=function(i){this.$element=t(i).addClass("navigation"),this.defaults={start:"xxs",end:"l"},this.$button=this.$element.children().first(),this.isShown=null,this.lastScroll=0,this.$button.length||(this.$button=t("<button/>").text("Menu").prependTo(this.$element));var a=this.$element.attr("id")||"navigation-"+t.pseudoUnique();this.$element.attr({id:a,role:"navigation"}),this.$button.attr({"aria-controls":a,"aria-expanded":!1}),this.$clone=this.$element.clone().removeAttr("id data-navigation").removeClass("canvas-navigation").addClass("visuallyhidden"),this.$clone.children("button").first().remove(),this.$clone.appendTo("body"),this.$button.on("click"+e,this.click.bind(this)),t(document).on("focusin"+e,this.focus.bind(this)).on("show.r.modal"+n,function(){this.hide(!0)}.bind(this))};r.prototype.toggle=function(){this[this.$element.hasClass("open")?"hide":"show"]()},r.prototype.show=function(){if(!this.isShown){var i=t.Event("show"+e),n=t.Event("shown"+e);if(this.$element.trigger(i),!i.isDefaultPrevented()){this.isShown=!0;var o=function(){this.transitioning=!1,this.$button.attr({"aria-expanded":!0}),t(document).on("keydown"+e,this.keydown.bind(this)),this.$element.trigger(n)}.bind(this);this.lastScroll=a.scrollTop(),t.toggleBodyLock(),this.$element.addClass("open visible").onTransitionEnd(o)}}},r.prototype.hide=function(i){if(this.isShown){var n=t.Event("hide"+e),o=t.Event("hidden"+e);if(this.$element.trigger(n),!n.isDefaultPrevented()){this.isShown=!1;var s=function(){this.$element.removeClass("visible"),this.$button.attr({"aria-expanded":!1}),this.transitioning=!1,t(document).off("keydown"+e),this.$element.trigger(o)}.bind(this);i||(t.toggleBodyLock(),a.scrollTop(this.lastScroll)),this.$element.removeClass("open").onTransitionEnd(s).ensureTransitionEnd()}}},r.prototype.click=function(){this.toggle()},r.prototype.keydown=function(t){t.which===s.ESCAPE&&this.$element.hasClass("open")&&this.hide()},r.prototype.focus=function(i){if(this.$element.hasClass("open")){if(!i.shiftKey&&i.target!==this.$element[0]&&!t.contains(this.$element[0],i.target))return this.$button.focus(),!1}else if(!i.shiftKey&&(i.target===this.$clone[0]||t.contains(this.$clone[0],i.target)))return this.$button.focus().click(),!1;return!0};var d=t.fn.navigation;t.fn.navigation=function(i){return this.each(function(){var e=t(this),n=e.data("r.navigation");n||e.data("r.navigation",n=new r(this)),"string"==typeof i&&/(show|hide)/.test(i)&&n[i]()})},t.fn.navigation.Constructor=r,t.fn.navigation.noConflict=function(){return t.fn.navigation=d,this};var h=function(){t("nav[data-navigation]").each(function(){var i=t(this);i.data("r.navigationLoaded")||(i.data("r.navigationLoaded",!0),i.navigation())})},l=t.debounce(h,500);t(document).on(["RBPinit"+e+n,o].join(" "),function(t){"RBPinit"===t.type?h():l()}).ready(function(){t(this).trigger("RBPinit"+e+n)}),i.RESPONSIVE_NAVIGATION=!0}}(jQuery,window,".r.navigation",".data-api"),function(t,i,e,n){"use strict";if(!i.RESPONSIVE_TABLE){var a=["RBPchanged"+e+n,"shown.r.modal"+n].join(" "),o=function(i){this.$element=t(i).addClass("table-list").attr("aria-role","grid"),this.$thead=this.$element.find("thead"),this.$tfoot=this.$element.find("tfoot"),this.$tbody=this.$element.find("tbody"),this.$headerColumns=this.$thead.find("th"),this.hasHeader=!0,this.$headerColumns.length||(this.hasHeader=!1,this.$element.addClass(".no-thead"),this.$headerColumns=this.$tbody.find("[scope=row]")),this.$headerColumns.attr({"aria-role":"columnheader","aria-hidden":"false"}),this.$footerColumns=this.$tfoot.find("th").attr({"aria-role":"columnheader","aria-hidden":"false"}),this.$bodyRows=this.$tbody.find("tr").attr("aria-role","row"),this.isAdded=null,this.add()};o.prototype.add=function(){if(!this.isAdded){var i=this,n=t.Event("add"+e),a=function(){i.$element.trigger(t.Event("added"+e))};i.$element.trigger(n),n.isDefaultPrevented()||(i.isAdded=!0,t.each(i.$bodyRows,function(){var e=i.hasHeader?"th, td":"td";t(this).find(e).each(function(n){var a=t(this),o="td"===e?a.prev("[scope=row]"):t(i.$headerColumns[n]),s=o.text(),r=o.attr("id")||"tablelist-"+t.pseudoUnique();if(o.attr("id",r),a.attr("data-thead",s),a.attr({"aria-role":"gridcell","aria-describedby":r}),i.$tfoot.length){var d=t(i.$footerColumns[n]),h=d.text(),l=d.attr("id")||"tablelist-"+t.pseudoUnique();a.attr("data-tfoot",h),a.attr({"aria-role":"gridcell","aria-describedby":l})}return!0})}),this.$element.redraw().addClass("fade-in"),this.$element.onTransitionEnd(a))}};var s=t.fn.tablelist;t.fn.tablelist=function(i){return this.each(function(){var e=t(this),n=e.data("r.tablelist"),a="object"==typeof i?i:null;n||e.data("r.tablelist",n=new o(this,a)),"string"==typeof i&&n[i]()})},t.fn.tablelist.Constructor=o,t.fn.tablelist.noConflict=function(){return t.fn.tablelist=s,this};var r=function(){t("table[data-table-list]").each(function(){var i=t(this);i.data("r.tableLoaded")||(i.data("r.tableLoaded",!0),i.tablelist(t.getDataOptions(i,{},"tablelist","r")))})},d=t.debounce(r,500);t(document).on(["RBPinit"+e+n,a].join(" "),function(t){"RBPinit"===t.type?r():d()}).ready(function(){t(this).trigger("RBPinit"+e+n)}),i.RESPONSIVE_TABLE=!0}}(jQuery,window,".r.tablelist",".data-api"),function(t,i,e,n){"use strict";if(!i.RESPONSIVE_TABS){var a=t.support.rtl,o=["RBPchanged"+e+n,"shown.r.modal"+n].join(" "),s={SPACE:32,LEFT:37,RIGHT:39},r=function(i){this.$element=t(i),this.tabbing=null;var e=this.$element.children("ul:first").attr("role","tablist"),n=e.children().attr("role","presentation"),a=this.$element.children(":not(ul)"),o=t.pseudoUnique(),s=e.find("[aria-selected=true]").parent().index(),r=s>-1;n.each(function(i){var e=t(this),n=e.children("a"),d=r&&i===s||!r&&0===i;n.attr({role:"tab",id:"tab-"+o+"-"+i,"aria-controls":"pane-"+o+"-"+i,"aria-selected":!!d,tabindex:0}),a.eq(i).attr({role:"tabpanel",id:"pane-"+o+"-"+i,"aria-labelledby":"tab-"+o+"-"+i,tabindex:d?0:-1})}),t(this.$element).on("click","ul[role=tablist] > li > [role=tab]",t.proxy(this.click,this)).on("keydown","ul[role=tablist] > li > [role=tab]",t.proxy(this.keydown,this))};r.prototype.show=function(i){var n=this.$element.children("ul").find("[aria-selected=true]"),a=n.closest("ul").children(),o=n.parent().index(),s=this;return!(i>a.length-1||i<0)&&(o!==i&&this.tab(o,i,function(i){var n=function(){s.tabbing=!1,i.siblings().addBack().removeClass("fade-out fade-in"),s.$element.trigger(t.Event("shown"+e,{relatedTarget:i[0]}))};i.onTransitionEnd(n)}))},r.prototype.tab=function(i,n,a){var o=t.Event("show"+e),s=this.$element,r=s.children("ul").children("li"),d=s.children(":not(ul)"),h=r.eq(n),l=d.eq(i),c=d.eq(n);s.trigger(o),this.tabbing||o.isDefaultPrevented()||(this.tabbing=!0,r.children("a").attr({"aria-selected":!1}),h.children("a").attr({"aria-selected":!0}).focus(),l.addClass("fade-out fade-in"),c.attr({tabIndex:0}).addClass("fade-out"),d.filter(".fade-in").attr({tabIndex:-1}).removeClass("fade-in"),c.redraw().addClass("fade-in"),a.call(this,c))},r.prototype.click=function(i){i.preventDefault(),i.stopPropagation();var e=t(i.target),n=e.parent(),a=n.index();this.show(a)},r.prototype.keydown=function(i){var e=i.which;if(e===s.SPACE||e===s.LEFT||e===s.RIGHT){i.preventDefault(),i.stopPropagation();var n=t(i.target),o=n.parent(),r=o.siblings().addBack(),d=r.length,h=o.index();if(e===s.SPACE)return void this.show(h);h=e===s.LEFT?a?h+1:h-1:a?h-1:h+1,h===d&&(h=0),h<0&&(h=d-1),this.show(h)}};var d=t.fn.tabs;t.fn.tabs=function(i){return this.each(function(){var e=t(this),n=e.data("r.tabs");n||e.data("r.tabs",n=new r(this)),"number"==typeof i&&n.show(i)})},t.fn.tabs.Constructor=r,t.fn.tabs.noConflict=function(){return t.fn.tabs=d,this};var h=function(){t("[data-tabs]").each(function(){var i=t(this);i.data("r.tabsLoaded")||(i.data("r.tabsLoaded",!0),i.tabs())})},l=t.debounce(h,500);t(document).on(["RBPinit"+e+n,o].join(" "),function(t){"RBPinit"===t.type?h():l()}).ready(function(){t(this).trigger("RBPinit"+e+n)}),i.RESPONSIVE_TABS=!0}}(jQuery,window,".r.tabs",".data-api");;
/* youtube-background v1.1.5 | https://github.com/stamat/youtube-background | MIT License */
(() => {
    // src/lib/buttons.js
    function buttonOn(buttonObj) {
        if (!buttonObj)
            return;
        buttonObj.element.classList.add(buttonObj.stateClassName);
        buttonObj.element.firstChild.classList.remove(buttonObj.stateChildClassNames[0]);
        buttonObj.element.firstChild.classList.add(buttonObj.stateChildClassNames[1]);
        buttonObj.element.setAttribute("aria-checked", false);
    }

    function buttonOff(buttonObj) {
        if (!buttonObj)
            return;
        buttonObj.element.classList.remove(buttonObj.stateClassName);
        buttonObj.element.firstChild.classList.add(buttonObj.stateChildClassNames[0]);
        buttonObj.element.firstChild.classList.remove(buttonObj.stateChildClassNames[1]);
        buttonObj.element.setAttribute("aria-checked", true);
    }

    function generateActionButton(obj, props) {
        const btn = document.createElement("button");
        btn.className = props.className;
        btn.innerHTML = props.innerHtml;
        btn.setAttribute("role", "switch");
        btn.firstChild.classList.add(props.stateChildClassNames[0]);
        btn.setAttribute("aria-checked", !props.initialState);
        props.element = btn;
        if (obj.params[props.condition_parameter] === props.initialState) {
            buttonOn(props);
        }
        btn.addEventListener("click", function (e) {
            if (this.classList.contains(props.stateClassName)) {
                buttonOff(props);
                obj[props.actions[0]]();
            } else {
                buttonOn(props);
                obj[props.actions[1]]();
            }
        });
        obj.buttons[props.name] = {
            element: btn,
            button_properties: props
        };
        obj.controls_element.appendChild(btn);
    }

    // node_modules/book-of-spells/src/helpers.mjs
    function stringToBoolean(str) {
        if (/^\s*(true|false)\s*$/i.test(str))
            return str === "true";
    }

    function stringToNumber(str) {
        if (/^\s*\d+\s*$/.test(str))
            return parseInt(str);
        if (/^\s*[\d.]+\s*$/.test(str))
            return parseFloat(str);
    }

    function stringToArray(str) {
        if (!/^\s*\[.*\]\s*$/.test(str))
            return;
        try {
            return JSON.parse(str);
        } catch (e) {
        }
    }

    function stringToObject(str) {
        if (!/^\s*\{.*\}\s*$/.test(str))
            return;
        try {
            return JSON.parse(str);
        } catch (e) {
        }
    }

    function stringToRegex(str) {
        if (!/^\s*\/.*\/g?i?\s*$/.test(str))
            return;
        try {
            return new RegExp(str);
        } catch (e) {
        }
    }

    function stringToType(str) {
        if (/^\s*null\s*$/.test(str))
            return null;
        const bool = stringToBoolean(str);
        if (bool !== void 0)
            return bool;
        return stringToNumber(str) || stringToArray(str) || stringToObject(str) || stringToRegex(str) || str;
    }

    function isArray(o) {
        return Array.isArray(o);
    }

    function isString(o) {
        return typeof o === "string";
    }

    function randomIntInclusive(min, max, safe = false) {
        min = Number(min);
        max = Number(max);
        if (isNaN(min) || isNaN(max))
            throw new TypeError("Both min and max must be numbers");
        if (min > max)
            [min, max] = [max, min];
        if (min === max)
            return min;
        min = Math.round(min);
        max = Math.round(max);
        const rand = safe ? random() : Math.random();
        return Math.floor(rand * (max - min + 1)) + min;
    }

    function fixed(number, digits) {
        if (!digits)
            return parseInt(number);
        return parseFloat(number.toFixed(digits));
    }

    function percentage(num, total) {
        if (!num || !total || Number.isNaN(num) || Number.isNaN(total))
            return 0;
        return num / total * 100;
    }

    function random() {
        if (!crypto)
            return Math.random();
        if (crypto.getRandomValues)
            return crypto.getRandomValues(new Uint32Array(1))[0] / 4294967295;
    }

    // node_modules/book-of-spells/src/regex.mjs
    var RE_YOUTUBE = /(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/ ]{11})/i;
    var RE_VIMEO = /(?:www\.|player\.)?vimeo.com\/(?:channels\/(?:\w+\/)?|groups\/(?:[^\/]*)\/videos\/|album\/(?:\d+)\/video\/|video\/|)(\d+)(?:[a-zA-Z0-9_\-]+)?/i;
    var RE_VIDEO = /\/([^\/]+\.(?:mp4|ogg|ogv|ogm|webm|avi))\s*$/i;

    // node_modules/book-of-spells/src/parsers.mjs
    function parseResolutionString(res) {
        const DEFAULT_RESOLUTION = 1.7777777778;
        if (!res || !res.length || /16[\:x\-\/]{1}9/i.test(res))
            return DEFAULT_RESOLUTION;
        const pts = res.split(/\s?[\:x\-\/]{1}\s?/i);
        if (pts.length < 2)
            return DEFAULT_RESOLUTION;
        const w = parseInt(pts[0]);
        const h = parseInt(pts[1]);
        if (w === 0 || h === 0)
            return DEFAULT_RESOLUTION;
        if (isNaN(w) || isNaN(h))
            return DEFAULT_RESOLUTION;
        return w / h;
    }

    // node_modules/book-of-spells/src/dom.mjs
    function query(selector, from = document) {
        if (selector instanceof Array || selector instanceof NodeList)
            return selector;
        if (selector instanceof Element)
            return [selector];
        if (from instanceof Element || from instanceof Document)
            return from.querySelectorAll(selector);
        if (isString(from))
            from = query(from);
        if (!from instanceof Array && !from instanceof NodeList)
            return [];
        const res = [];
        for (const element of from) {
            res.push(...element.querySelectorAll(selector));
        }
        return res;
    }

    function proportionalParentCoverResize(elements, ratio = 1, offset = 0) {
        if (elements instanceof Element)
            elements = [elements];
        if (typeof elements === "string")
            elements = query(elements);
        for (const element of elements) {
            const h = element.parentNode.offsetHeight + offset;
            const w = element.parentNode.offsetWidth + offset;
            if (ratio > w / h) {
                element.style.width = h * ratio + "px";
                element.style.height = h + "px";
            } else {
                element.style.width = w + "px";
                element.style.height = w / ratio + "px";
            }
        }
    }

    // node_modules/book-of-spells/src/browser.mjs
    function isUserAgentMobile(str) {
        return /\b(BlackBerry|webOS|iPhone|IEMobile)\b/i.test(str) || /\b(Android|Windows Phone|iPad|iPod)\b/i.test(str);
    }

    function isMobile() {
        if ("maxTouchPoints" in navigator)
            return navigator.maxTouchPoints > 0;
        if ("matchMedia" in window)
            return !!matchMedia("(pointer:coarse)").matches;
        if ("orientation" in window)
            return true;
        return isUserAgentMobile(navigator.userAgent);
    }

    // src/lib/super-video-background.js
    var SuperVideoBackground = class {
        constructor(elem, params, id, uid, type, factoryInstance) {
            if (!id)
                return;
            this.is_mobile = isMobile();
            this.type = type;
            this.id = id;
            this.factoryInstance = factoryInstance;
            this.element = elem;
            this.playerElement = null;
            this.uid = uid;
            this.element.setAttribute("data-vbg-uid", uid);
            this.buttons = {};
            this.isIntersecting = false;
            this.paused = false;
            this.muted = false;
            this.currentState = "notstarted";
            this.initialPlay = false;
            this.initialVolume = false;
            this.volume = 1;
            this.params = {};
            const DEFAULTS = {
                "pause": false,
                //deprecated
                "play-button": false,
                "mute-button": false,
                "autoplay": true,
                "muted": true,
                "loop": true,
                "mobile": true,
                "load-background": false,
                "resolution": "16:9",
                "inline-styles": true,
                "fit-box": false,
                "offset": 100,
                // since showinfo is deprecated and ignored after September 25, 2018. we add +100 to hide it in the overflow
                "start-at": 0,
                "end-at": 0,
                "poster": null,
                "always-play": false,
                "volume": 1,
                "no-cookie": true,
                "force-on-low-battery": false,
                "lazyloading": false
            };
            this.params = this.parseProperties(params, DEFAULTS, this.element, ["data-ytbg-", "data-vbg-"]);
            if (this.params.pause) {
                this.params["play-button"] = this.params.pause;
            }
            this.params.resolution_mod = parseResolutionString(this.params.resolution);
            this.muted = this.params.muted;
            this.volume = this.params.volume;
            this.currentTime = this.params["start-at"] || 0;
            this.duration = this.params["end-at"] || 0;
            this.percentComplete = 0;
            if (this.params["start-at"])
                this.percentComplete = this.timeToPercentage(this.params["start-at"]);
            this.buildWrapperHTML();
            if (this.is_mobile && !this.params.mobile)
                return;
            if (this.params["play-button"]) {
                generateActionButton(this, {
                    name: "playing",
                    className: "play-toggle",
                    innerHtml: '<i class="fa"></i>',
                    initialState: !this.paused,
                    stateClassName: "paused",
                    condition_parameter: "paused",
                    stateChildClassNames: ["fa-pause-circle", "fa-play-circle"],
                    actions: ["play", "pause"]
                });
            }
            if (this.params["mute-button"]) {
                generateActionButton(this, {
                    name: "muted",
                    className: "mute-toggle",
                    innerHtml: '<i class="fa"></i>',
                    initialState: this.muted,
                    stateClassName: "muted",
                    condition_parameter: "muted",
                    stateChildClassNames: ["fa-volume-up", "fa-volume-mute"],
                    actions: ["unmute", "mute"]
                });
            }
        }

        timeToPercentage(time) {
            if (time <= this.params["start-at"])
                return 0;
            if (time >= this.duration)
                return 100;
            if (time <= 0)
                return 0;
            time -= this.params["start-at"];
            const duration = this.duration - this.params["start-at"];
            return percentage(time, duration);
        }

        percentageToTime(percentage2) {
            if (!this.duration)
                return this.params["start-at"] || 0;
            if (percentage2 > 100)
                return this.duration;
            if (percentage2 <= 0)
                return this.params["start-at"] || 0;
            const duration = this.duration - this.params["start-at"];
            let time = percentage2 * duration / 100;
            time = fixed(time, 3);
            if (time > duration)
                time = duration;
            if (this.params["start-at"])
                time += this.params["start-at"];
            return time;
        }

        resize(element) {
            if (!this.params["fit-box"])
                proportionalParentCoverResize(element || this.playerElement, this.params.resolution_mod, this.params.offset);
            this.dispatchEvent("video-background-resize");
        }

        stylePlayerElement(element) {
            if (!element)
                return;
            if (this.params["inline-styles"]) {
                element.style.top = "50%";
                element.style.left = "50%";
                element.style.transform = "translateX(-50%) translateY(-50%)";
                element.style.position = "absolute";
                element.style.opacity = 0;
            }
            if (this.params["fit-box"]) {
                element.style.width = "100%";
                element.style.height = "100%";
            }
        }

        buildWrapperHTML() {
            const parent = this.element.parentNode;
            this.element.classList.add("youtube-background", "video-background");
            const wrapper_styles = {
                "height": "100%",
                "width": "100%",
                "z-index": "0",
                "position": "absolute",
                "overflow": "hidden",
                "top": 0,
                // added by @insad
                "left": 0,
                "bottom": 0,
                "right": 0
            };
            if (!this.params["mute-button"]) {
                wrapper_styles["pointer-events"] = "none";
            }
            if (this.params["load-background"] || this.params["poster"]) {
                this.loadBackground(this.id);
                if (this.params["poster"])
                    wrapper_styles["background-image"] = `url(${this.params["poster"]})`;
                wrapper_styles["background-size"] = "cover";
                wrapper_styles["background-repeat"] = "no-repeat";
                wrapper_styles["background-position"] = "center";
            }
            if (this.params["inline-styles"]) {
                for (let property in wrapper_styles) {
                    this.element.style[property] = wrapper_styles[property];
                }
                if (!["absolute", "fixed", "relative", "sticky"].indexOf(parent.style.position)) {
                    parent.style.position = "relative";
                }
            }
            if (this.params["play-button"] || this.params["mute-button"]) {
                const controls = document.createElement("div");
                controls.className = "video-background-controls";
                controls.style.position = "absolute";
                controls.style.top = "10px";
                controls.style.right = "10px";
                controls.style["z-index"] = 2;
                this.controls_element = controls;
                parent.appendChild(controls);
            }
            return this.element;
        }

        loadBackground(id) {
            if (!this.params["load-background"])
                return;
            if (!id)
                return;
            if (this.type === "youtube")
                this.element.style["background-image"] = `url(https://img.youtube.com/vi/${id}/hqdefault.jpg)`;
            if (this.type === "vimeo")
                this.element.style["background-image"] = `url(https://vumbnail.com/${id}.jpg)`;
        }

        destroy() {
            this.playerElement.remove();
            this.element.classList.remove("youtube-background", "video-background");
            this.element.removeAttribute("data-vbg-uid");
            this.element.style = "";
            if (this.params["play-button"] || this.params["mute-button"]) {
                this.controls_element.remove();
            }
            if (this.timeUpdateTimer)
                clearInterval(this.timeUpdateTimer);
            this.dispatchEvent("video-background-destroyed");
        }

        setDuration(duration) {
            if (this.duration === duration)
                return;
            if (this.params["end-at"]) {
                if (duration > this.params["end-at"]) {
                    this.duration = this.params["end-at"];
                    return;
                }
                if (duration < this.params["end-at"]) {
                    this.duration = duration;
                    return;
                }
            } else {
                this.duration = duration;
                return;
            }
            if (duration <= 0)
                this.duration = this.params["end-at"];
        }

        setStartAt(startAt) {
            this.params["start-at"] = startAt;
        }

        setEndAt(endAt) {
            this.params["end-at"] = endAt;
            if (this.duration > endAt)
                this.duration = endAt;
            if (this.currentTime > endAt)
                this.onVideoEnded();
        }

        dispatchEvent(name) {
            this.element.dispatchEvent(new CustomEvent(name, {bubbles: true, detail: this}));
        }

        shouldPlay() {
            if (this.currentState === "ended" && !this.params.loop)
                return false;
            if (this.params["always-play"] && this.currentState !== "playing")
                return true;
            if (this.isIntersecting && this.params.autoplay && this.currentState !== "playing")
                return true;
            return false;
        }

        mobileLowBatteryAutoplayHack() {
            if (!this.params["force-on-low-battery"])
                return;
            if (!this.is_mobile && this.params.mobile)
                return;
            const forceAutoplay = function () {
                if (!this.initialPlay && this.params.autoplay && this.params.muted) {
                    this.softPlay();
                    if (!this.isIntersecting && !this.params["always-play"]) {
                        this.softPause();
                    }
                }
            };
            document.addEventListener("touchstart", forceAutoplay.bind(this), {once: true});
        }

        parseProperties(params, defaults, element, attr_prefix) {
            let res_params = {};
            if (!params) {
                res_params = defaults;
            } else {
                for (let k in defaults) {
                    res_params[k] = !params.hasOwnProperty(k) ? defaults[k] : params[k];
                }
            }
            if (!element)
                return res_params;
            for (let k in res_params) {
                let data;
                if (isArray(attr_prefix)) {
                    for (let i = 0; i < attr_prefix.length; i++) {
                        const temp_data = element.getAttribute(attr_prefix[i] + k);
                        if (temp_data) {
                            data = temp_data;
                            break;
                        }
                    }
                } else {
                    data = element.getAttribute(attr_prefix + k);
                }
                if (data !== void 0 && data !== null) {
                    res_params[k] = stringToType(data);
                }
            }
            return res_params;
        }
    };

    // src/lib/youtube-background.js
    var YoutubeBackground = class extends SuperVideoBackground {
        constructor(elem, params, id, uid, factoryInstance) {
            super(elem, params, id, uid, "youtube", factoryInstance);
            if (!id)
                return;
            if (this.is_mobile && !this.params.mobile)
                return;
            this.injectScript();
            this.player = null;
            this.injectPlayer();
            this.STATES = {
                "-1": "notstarted",
                "0": "ended",
                "1": "playing",
                "2": "paused",
                "3": "buffering",
                "5": "cued"
            };
            this.timeUpdateTimer = null;
            this.timeUpdateInterval = 250;
            this.initYTPlayer();
        }

        startTimeUpdateTimer() {
            if (this.timeUpdateTimer)
                return;
            this.timeUpdateTimer = setInterval(this.onVideoTimeUpdate.bind(this), this.timeUpdateInterval);
        }

        stopTimeUpdateTimer() {
            clearInterval(this.timeUpdateTimer);
            this.timeUpdateTimer = null;
        }

        convertState(state) {
            return this.STATES[state];
        }

        initYTPlayer() {
            if (!window.hasOwnProperty("YT") || this.player !== null)
                return;
            this.player = new YT.Player(this.uid, {
                events: {
                    "onReady": this.onVideoPlayerReady.bind(this),
                    "onStateChange": this.onVideoStateChange.bind(this)
                    // 'onError': this.onVideoError.bind(this)
                }
            });
            if (this.volume !== 1 && !this.muted)
                this.setVolume(this.volume);
        }

        onVideoError(event) {
            console.error(event);
        }

        injectScript() {
            if (window.hasOwnProperty("YT") || document.querySelector('script[src="https://www.youtube.com/player_api"]'))
                return;
            const tag = document.createElement("script");
            tag.src = "https://www.youtube.com/player_api";
            const firstScriptTag = document.getElementsByTagName("script")[0];
            firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
        }

        generatePlayerElement() {
            const playerElement = document.createElement("iframe");
            playerElement.setAttribute("frameborder", 0);
            playerElement.setAttribute("allow", "autoplay; mute");
            if (this.params["lazyloading"])
                playerElement.setAttribute("loading", "lazy");
            return playerElement;
        }

        generateSrcURL(id) {
            let site = "https://www.youtube.com/embed/";
            if (this.params["no-cookie"]) {
                site = "https://www.youtube-nocookie.com/embed/";
            }
            let src = `${site}${id}?&enablejsapi=1&disablekb=1&controls=0&rel=0&iv_load_policy=3&cc_load_policy=0&playsinline=1&showinfo=0&modestbranding=1&fs=0`;
            if (this.params.muted) {
                src += "&mute=1";
            }
            if (this.params.autoplay && (this.params["always-play"] || this.isIntersecting)) {
                src += "&autoplay=1";
            }
            if (this.params.loop) {
                src += "&loop=1";
            }
            return src;
        }

        injectPlayer() {
            this.playerElement = this.generatePlayerElement();
            this.src = this.generateSrcURL(this.id);
            this.playerElement.src = this.src;
            this.playerElement.id = this.uid;
            this.stylePlayerElement(this.playerElement);
            this.element.appendChild(this.playerElement);
            this.resize(this.playerElement);
        }

        /* ===== API ===== */
        setSource(url) {
            const pts = url.match(RE_YOUTUBE);
            if (!pts || !pts.length)
                return;
            this.id = pts[1];
            this.src = this.generateSrcURL(this.id);
            this.playerElement.src = this.src;
            if (this.element.hasAttribute("data-vbg"))
                this.element.setAttribute("data-vbg", this.src);
            if (this.element.hasAttribute("data-ytbg"))
                this.element.setAttribute("data-ytbg", this.src);
            this.loadBackground(this.id);
        }

        onVideoTimeUpdate() {
            const ctime = this.player.getCurrentTime();
            if (ctime === this.currentTime)
                return;
            this.currentTime = ctime;
            this.percentComplete = this.timeToPercentage(this.currentTime);
            if (this.params["end-at"] && this.duration && this.currentTime >= this.duration) {
                this.currentState = "ended";
                this.dispatchEvent("video-background-state-change");
                this.onVideoEnded();
                this.stopTimeUpdateTimer();
                return;
            }
            this.dispatchEvent("video-background-time-update");
        }

        onVideoPlayerReady() {
            this.mobileLowBatteryAutoplayHack();
            if (this.params.autoplay && (this.params["always-play"] || this.isIntersecting)) {
                if (this.params["start-at"])
                    this.seekTo(this.params["start-at"]);
                this.player.playVideo();
            }
            this.setDuration(this.player.getDuration());
            this.dispatchEvent("video-background-ready");
        }

        onVideoStateChange(event) {
            this.currentState = this.convertState(event.data);
            if (this.currentState === "ended")
                this.onVideoEnded();
            if (this.currentState === "notstarted" && this.params.autoplay) {
                this.seekTo(this.params["start-at"]);
                this.player.playVideo();
            }
            if (this.currentState === "playing")
                this.onVideoPlay();
            if (this.currentState === "paused")
                this.onVideoPause();
            this.dispatchEvent("video-background-state-change");
        }

        onVideoPlay() {
            if (!this.initialPlay) {
                this.initialPlay = true;
                this.playerElement.style.opacity = 1;
            }
            const seconds = this.player.getCurrentTime();
            if (this.params["start-at"] && seconds < this.params["start-at"]) {
                this.seekTo(this.params["start-at"]);
            }
            if (this.duration && seconds >= this.duration) {
                this.seekTo(this.params["start-at"]);
            }
            if (!this.duration) {
                this.setDuration(this.player.getDuration());
            }
            this.dispatchEvent("video-background-play");
            this.startTimeUpdateTimer();
        }

        onVideoPause() {
            this.stopTimeUpdateTimer();
            this.dispatchEvent("video-background-pause");
        }

        onVideoEnded() {
            this.dispatchEvent("video-background-ended");
            if (!this.params.loop)
                return this.pause();
            this.seekTo(this.params["start-at"]);
            this.player.playVideo();
        }

        seek(percentage2) {
            this.seekTo(this.percentageToTime(percentage2), true);
        }

        seekTo(seconds, allowSeekAhead = true) {
            if (!this.player)
                return;
            this.player.seekTo(seconds, allowSeekAhead);
            this.dispatchEvent("video-background-seeked");
        }

        softPause() {
            if (!this.player || this.currentState === "paused")
                return;
            this.stopTimeUpdateTimer();
            this.player.pauseVideo();
        }

        softPlay() {
            if (!this.player || this.currentState === "playing")
                return;
            this.player.playVideo();
        }

        play() {
            if (!this.player)
                return;
            this.paused = false;
            this.player.playVideo();
        }

        pause() {
            if (!this.player)
                return;
            this.paused = true;
            this.stopTimeUpdateTimer();
            this.player.pauseVideo();
        }

        unmute() {
            if (!this.player)
                return;
            this.muted = false;
            if (!this.initialVolume) {
                this.initialVolume = true;
                this.setVolume(this.params.volume);
            }
            this.player.unMute();
            this.dispatchEvent("video-background-unmute");
        }

        mute() {
            if (!this.player)
                return;
            this.muted = true;
            this.player.mute();
            this.dispatchEvent("video-background-mute");
        }

        getVolume() {
            if (!this.player)
                return;
            return this.player.getVolume() / 100;
        }

        setVolume(volume) {
            if (!this.player)
                return;
            this.volume = volume;
            this.player.setVolume(volume * 100);
            this.dispatchEvent("video-background-volume-change");
        }
    };

    // src/lib/vimeo-background.js
    var VimeoBackground = class extends SuperVideoBackground {
        constructor(elem, params, id, uid, factoryInstance) {
            super(elem, params, id, uid, "vimeo", factoryInstance);
            if (!id)
                return;
            if (this.is_mobile && !this.params.mobile)
                return;
            this.injectScript();
            this.player = null;
            this.injectPlayer();
            this.initVimeoPlayer();
        }

        injectScript() {
            if (window.hasOwnProperty("Vimeo") || document.querySelector('script[src="https://player.vimeo.com/api/player.js"]'))
                return;
            const tag = document.createElement("script");
            if (window.hasOwnProperty("onVimeoIframeAPIReady") && typeof window.onVimeoIframeAPIReady === "function")
                tag.addEventListener("load", () => {
                    window.onVimeoIframeAPIReady();
                });
            tag.src = "https://player.vimeo.com/api/player.js";
            const firstScriptTag = document.getElementsByTagName("script")[0];
            firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
        }

        initVimeoPlayer() {
            if (!window.hasOwnProperty("Vimeo") || this.player !== null)
                return;
            this.player = new Vimeo.Player(this.playerElement);
            this.player.on("loaded", this.onVideoPlayerReady.bind(this));
            this.player.on("ended", this.onVideoEnded.bind(this));
            this.player.on("play", this.onVideoPlay.bind(this));
            this.player.on("pause", this.onVideoPause.bind(this));
            this.player.on("bufferstart", this.onVideoBuffering.bind(this));
            this.player.on("timeupdate", this.onVideoTimeUpdate.bind(this));
            if (this.volume !== 1 && !this.muted)
                this.setVolume(this.volume);
        }

        onVideoError(event) {
            console.error(event);
        }

        generatePlayerElement() {
            const playerElement = document.createElement("iframe");
            playerElement.setAttribute("frameborder", 0);
            playerElement.setAttribute("allow", "autoplay; mute");
            if (this.params["lazyloading"])
                playerElement.setAttribute("loading", "lazy");
            return playerElement;
        }

        generateSrcURL(id) {
            let src = "https://player.vimeo.com/video/" + id + "?background=1&controls=0";
            if (this.params.muted) {
                src += "&muted=1";
            }
            if (this.params.autoplay && (this.params["always-play"] || this.isIntersecting)) {
                src += "&autoplay=1";
            }
            if (this.params.loop) {
                src += "&loop=1&autopause=0";
            }
            if (this.params["no-cookie"]) {
                src += "&dnt=1";
            }
            if (this.params["start-at"]) {
                src += "#t=" + this.params["start-at"] + "s";
            }
            return src;
        }

        injectPlayer() {
            this.playerElement = this.generatePlayerElement();
            this.src = this.generateSrcURL(this.id);
            this.playerElement.src = this.src;
            this.playerElement.id = this.uid;
            this.stylePlayerElement(this.playerElement);
            this.element.appendChild(this.playerElement);
            this.resize(this.playerElement);
        }

        updateState(state) {
            this.currentState = state;
            this.dispatchEvent("video-background-state-change");
        }

        /* ===== API ===== */
        setSource(url) {
            const pts = url.match(RE_VIMEO);
            if (!pts || !pts.length)
                return;
            this.id = pts[1];
            this.src = this.generateSrcURL(this.id);
            this.playerElement.src = this.src;
            if (this.element.hasAttribute("data-vbg"))
                this.element.setAttribute("data-vbg", this.src);
            if (this.element.hasAttribute("data-ytbg"))
                this.element.setAttribute("data-ytbg", this.src);
            this.loadBackground(this.id);
        }

        onVideoPlayerReady() {
            this.mobileLowBatteryAutoplayHack();
            if (this.params["start-at"])
                this.seekTo(this.params["start-at"]);
            if (this.params.autoplay && (this.params["always-play"] || this.isIntersecting)) {
                this.player.play();
            }
            this.player.getDuration().then((duration) => {
                this.setDuration(duration);
            });
            this.dispatchEvent("video-background-ready");
        }

        onVideoEnded() {
            this.updateState("ended");
            this.dispatchEvent("video-background-ended");
            if (!this.params.loop)
                return this.pause();
            this.seekTo(this.params["start-at"]);
            this.updateState("playing");
            this.dispatchEvent("video-background-play");
        }

        onVideoTimeUpdate(event) {
            this.currentTime = event.seconds;
            this.percentComplete = this.timeToPercentage(event.seconds);
            this.dispatchEvent("video-background-time-update");
            this.setDuration(event.duration);
            if (this.params["end-at"] && this.duration && event.seconds >= this.duration) {
                this.onVideoEnded();
            }
        }

        onVideoBuffering() {
            this.updateState("buffering");
        }

        onVideoPlay(event) {
            this.setDuration(event.duration);
            if (!this.initialPlay) {
                this.initialPlay = true;
                this.playerElement.style.opacity = 1;
                this.player.setLoop(this.params.loop);
                if (!(this.params.autoplay && (this.params["always-play"] || this.isIntersecting))) {
                    return this.player.pause();
                }
            }
            const seconds = event.seconds;
            if (this.params["start-at"] && seconds < this.params["start-at"]) {
                this.seekTo(this.params["start-at"]);
            }
            if (this.duration && seconds >= this.duration) {
                this.seekTo(this.params["start-at"]);
            }
            this.updateState("playing");
            this.dispatchEvent("video-background-play");
        }

        onVideoPause() {
            this.updateState("paused");
            this.dispatchEvent("video-background-pause");
        }

        seek(percentage2) {
            this.seekTo(this.percentageToTime(percentage2));
        }

        seekTo(time) {
            if (!this.player)
                return;
            this.player.setCurrentTime(time);
            this.dispatchEvent("video-background-seeked");
        }

        softPause() {
            if (!this.player || this.currentState === "paused")
                return;
            this.player.pause();
        }

        softPlay() {
            if (!this.player || this.currentState === "playing")
                return;
            this.player.play();
        }

        play() {
            if (!this.player)
                return;
            this.paused = false;
            this.player.play();
        }

        pause() {
            if (!this.player)
                return;
            this.paused = true;
            this.player.pause();
        }

        unmute() {
            if (!this.player)
                return;
            this.muted = false;
            if (!this.initialVolume) {
                this.initialVolume = true;
                this.setVolume(this.params.volume);
            }
            this.player.setMuted(false);
            this.dispatchEvent("video-background-unmute");
        }

        mute() {
            if (!this.player)
                return;
            this.muted = true;
            this.player.setMuted(true);
            this.dispatchEvent("video-background-mute");
        }

        getVolume() {
            if (!this.player)
                return;
            return this.player.getVolume();
        }

        setVolume(volume) {
            if (!this.player)
                return;
            this.volume = volume;
            this.player.setVolume(volume);
            this.dispatchEvent("video-background-volume-change");
        }
    };

    // src/lib/video-background.js
    var VideoBackground = class extends SuperVideoBackground {
        constructor(elem, params, vid_data, uid, factoryInstance) {
            super(elem, params, vid_data.link, uid, "video", factoryInstance);
            if (!vid_data || !vid_data.link)
                return;
            if (this.is_mobile && !this.params.mobile)
                return;
            this.src = vid_data.link;
            this.ext = /(?:\.([^.]+))?$/.exec(vid_data.id)[1];
            this.uid = uid;
            this.element.setAttribute("data-vbg-uid", uid);
            this.player = null;
            this.buttons = {};
            this.MIME_MAP = {
                "ogv": "video/ogg",
                "ogm": "video/ogg",
                "ogg": "video/ogg",
                "avi": "video/avi",
                "mp4": "video/mp4",
                "webm": "video/webm"
            };
            this.mime = this.MIME_MAP[this.ext.toLowerCase()];
            this.injectPlayer();
            this.mobileLowBatteryAutoplayHack();
            this.dispatchEvent("video-background-ready");
        }

        generatePlayerElement() {
            const playerElement = document.createElement("video");
            playerElement.setAttribute("playsinline", "");
            if (this.params.loop)
                playerElement.setAttribute("loop", "");
            if (this.params.autoplay && (this.params["always-play"] || this.isIntersecting)) {
                playerElement.setAttribute("autoplay", "");
                playerElement.autoplay = true;
            }
            if (this.muted) {
                playerElement.setAttribute("muted", "");
                playerElement.muted = true;
            }
            if (this.params["lazyloading"])
                playerElement.setAttribute("loading", "lazy");
            return playerElement;
        }

        injectPlayer() {
            this.player = this.generatePlayerElement();
            this.playerElement = this.player;
            if (this.volume !== 1 && !this.muted)
                this.setVolume(this.volume);
            this.playerElement.setAttribute("id", this.uid);
            this.stylePlayerElement(this.playerElement);
            this.player.addEventListener("loadedmetadata", this.onVideoLoadedMetadata.bind(this));
            this.player.addEventListener("durationchange", this.onVideoLoadedMetadata.bind(this));
            this.player.addEventListener("canplay", this.onVideoCanPlay.bind(this));
            this.player.addEventListener("timeupdate", this.onVideoTimeUpdate.bind(this));
            this.player.addEventListener("play", this.onVideoPlay.bind(this));
            this.player.addEventListener("pause", this.onVideoPause.bind(this));
            this.player.addEventListener("waiting", this.onVideoBuffering.bind(this));
            this.player.addEventListener("ended", this.onVideoEnded.bind(this));
            this.element.appendChild(this.playerElement);
            const source = document.createElement("source");
            source.setAttribute("src", this.src);
            source.setAttribute("type", this.mime);
            this.playerElement.appendChild(source);
            this.resize(this.playerElement);
        }

        updateState(state) {
            this.currentState = state;
            this.dispatchEvent("video-background-state-change");
        }

        /* ===== API ===== */
        setSource(url) {
            const pts = url.match(RE_VIDEO);
            if (!pts || !pts.length)
                return;
            this.id = pts[1];
            this.ext = /(?:\.([^.]+))?$/.exec(this.id)[1];
            this.mime = this.MIME_MAP[this.ext.toLowerCase()];
            this.playerElement.innerHTML = "";
            const source = document.createElement("source");
            source.setAttribute("src", url);
            source.setAttribute("type", this.mime);
            this.playerElement.appendChild(source);
            this.src = url;
            if (this.element.hasAttribute("data-vbg"))
                this.element.setAttribute("data-vbg", this.src);
            if (this.element.hasAttribute("data-ytbg"))
                this.element.setAttribute("data-ytbg", this.src);
        }

        onVideoLoadedMetadata() {
            this.setDuration(this.player.duration);
        }

        onVideoCanPlay() {
            this.setDuration(this.player.duration);
        }

        onVideoTimeUpdate() {
            this.currentTime = this.player.currentTime;
            this.percentComplete = this.timeToPercentage(this.player.currentTime);
            this.dispatchEvent("video-background-time-update");
            if (this.params["end-at"] && this.currentTime >= this.duration) {
                this.onVideoEnded();
            }
        }

        onVideoPlay() {
            if (!this.initialPlay) {
                this.initialPlay = true;
                this.playerElement.style.opacity = 1;
            }
            const seconds = this.player.currentTime;
            if (this.params["start-at"] && seconds <= this.params["start-at"]) {
                this.seekTo(this.params["start-at"]);
            }
            if (this.duration && seconds >= this.duration) {
                this.seekTo(this.params["start-at"]);
            }
            this.updateState("playing");
            this.dispatchEvent("video-background-play");
        }

        onVideoPause() {
            this.updateState("paused");
            this.dispatchEvent("video-background-pause");
        }

        onVideoEnded() {
            this.updateState("ended");
            this.dispatchEvent("video-background-ended");
            if (!this.params.loop)
                return this.pause();
            this.seekTo(this.params["start-at"]);
            this.onVideoPlay();
        }

        onVideoBuffering() {
            this.updateState("buffering");
        }

        seek(percentage2) {
            this.seekTo(this.percentageToTime(percentage2));
        }

        seekTo(seconds) {
            if (!this.player)
                return;
            if (this.player.hasOwnProperty("fastSeek")) {
                this.player.fastSeek(seconds);
                return;
            }
            this.player.currentTime = seconds;
            this.dispatchEvent("video-background-seeked");
        }

        softPause() {
            if (!this.player || this.currentState === "paused")
                return;
            this.player.pause();
        }

        softPlay() {
            if (!this.player || this.currentState === "playing")
                return;
            this.player.play();
        }

        play() {
            if (!this.player)
                return;
            this.paused = false;
            this.player.play();
        }

        pause() {
            if (!this.player)
                return;
            this.paused = true;
            this.player.pause();
        }

        unmute() {
            if (!this.player)
                return;
            this.muted = false;
            this.player.muted = false;
            if (!this.initialVolume) {
                this.initialVolume = true;
                this.setVolume(this.params.volume);
            }
            this.dispatchEvent("video-background-unmute");
        }

        mute() {
            if (!this.player)
                return;
            this.muted = true;
            this.player.muted = true;
            this.dispatchEvent("video-background-mute");
        }

        getVolume() {
            if (!this.player)
                return;
            return this.player.volume;
        }

        setVolume(volume) {
            if (!this.player)
                return;
            this.volume = volume;
            this.player.volume = volume;
            this.dispatchEvent("video-background-volume-change");
        }
    };

    // src/video-backgrounds.js
    var VideoBackgrounds = class {
        constructor(selector, params) {
            this.elements = selector;
            if (this.elements instanceof Element)
                this.elements = [this.elements];
            if (typeof this.elements === "string")
                this.elements = document.querySelectorAll(selector);
            this.index = {};
            const self = this;
            this.intersectionObserver = null;
            if ("IntersectionObserver" in window) {
                this.intersectionObserver = new IntersectionObserver(function (entries) {
                    entries.forEach(function (entry) {
                        const uid = entry.target.getAttribute("data-vbg-uid");
                        if (uid && self.index.hasOwnProperty(uid) && entry.isIntersecting) {
                            self.index[uid].isIntersecting = true;
                            try {
                                if (self.index[uid].player && !self.index[uid].paused)
                                    self.index[uid].softPlay();
                            } catch (e) {
                            }
                        } else {
                            self.index[uid].isIntersecting = false;
                            try {
                                if (self.index[uid].player)
                                    self.index[uid].softPause();
                            } catch (e) {
                            }
                        }
                    });
                });
            }
            this.resizeObserver = null;
            if ("ResizeObserver" in window) {
                this.resizeObserver = new ResizeObserver(function (entries) {
                    entries.forEach(function (entry) {
                        const uid = entry.target.getAttribute("data-vbg-uid");
                        if (uid && self.index.hasOwnProperty(uid)) {
                            window.requestAnimationFrame(() => self.index[uid].resize());
                        }
                    });
                });
            } else {
                window.addEventListener("resize", function () {
                    for (let k in self.index) {
                        window.requestAnimationFrame(() => self.index[k].resize(self.index[k].playerElement));
                    }
                });
            }
            this.initPlayers();
            if (!this.elements || !this.elements.length)
                return;
            for (let i = 0; i < this.elements.length; i++) {
                const element = this.elements[i];
                this.add(element, params);
            }
            document.addEventListener("visibilitychange", this.onVisibilityChange.bind(this));
        }

        onVisibilityChange() {
            if (document.hidden)
                return;
            for (let k in this.index) {
                const instance = this.index[k];
                if (instance.shouldPlay()) {
                    instance.softPlay();
                }
            }
        }

        add(element, params) {
            if (!element)
                return;
            if (element.hasAttribute("data-vbg-uid"))
                return;
            if (!this.intersectionObserver) {
                if (!params)
                    params = {};
                params["always-play"] = true;
            }
            const link = element.getAttribute("data-youtube") || element.getAttribute("data-vbg");
            const vid_data = this.getVidID(link);
            if (!vid_data)
                return;
            const uid = this.generateUID(vid_data.id);
            if (!uid)
                return;
            switch (vid_data.type) {
                case "YOUTUBE":
                    const yb = new YoutubeBackground(element, params, vid_data.id, uid, this);
                    this.index[uid] = yb;
                    break;
                case "VIMEO":
                    const vm = new VimeoBackground(element, params, vid_data.id, uid, this);
                    this.index[uid] = vm;
                    break;
                case "VIDEO":
                    const vid = new VideoBackground(element, params, vid_data, uid, this);
                    this.index[uid] = vid;
                    break;
            }
            if (this.resizeObserver) {
                this.resizeObserver.observe(element);
            }
            if (!this.index[uid].params["always-play"] && this.intersectionObserver) {
                this.intersectionObserver.observe(element);
            }
        }

        destroy(element) {
            const uid = element.uid || element.getAttribute("data-vbg-uid");
            if (uid && this.index.hasOwnProperty(uid)) {
                if (!this.index[uid].params["always-play"] && this.intersectionObserver)
                    this.intersectionObserver.unobserve(element);
                if (this.resizeObserver)
                    this.resizeObserver.unobserve(element);
                this.index[uid].destroy();
                delete this.index[uid];
            }
        }

        destroyAll() {
            for (let k in this.index) {
                this.destroy(this.index[k].playerElement);
            }
        }

        getVidID(link) {
            if (link === void 0 && link === null)
                return;
            this.re = {};
            this.re.YOUTUBE = RE_YOUTUBE;
            this.re.VIMEO = RE_VIMEO;
            this.re.VIDEO = RE_VIDEO;
            for (let k in this.re) {
                const pts = link.match(this.re[k]);
                if (pts && pts.length) {
                    this.re[k].lastIndex = 0;
                    return {
                        id: pts[1],
                        type: k,
                        regex_pts: pts,
                        link
                    };
                }
            }
            return;
        }

        generateUID(pref) {
            pref = pref.replace(/[^a-zA-Z0-9\-_]/g, "-");
            pref = pref.replace(/-{2,}/g, "-");
            pref = pref.replace(/^-+/, "").replace(/-+$/, "");
            pref = "vbg-" + pref;
            let uid = pref + "-" + randomIntInclusive(0, 9999);
            while (this.index.hasOwnProperty(uid)) {
                uid = pref + "-" + randomIntInclusive(0, 9999);
            }
            return uid;
        }

        get(element) {
            const uid = typeof element === "string" ? element : element.getAttribute("data-vbg-uid");
            if (uid && this.index.hasOwnProperty(uid))
                return this.index[uid];
        }

        pauseAll() {
            for (let k in this.index) {
                this.index[k].pause();
            }
        }

        playAll() {
            for (let k in this.index) {
                this.index[k].play();
            }
        }

        muteAll() {
            for (let k in this.index) {
                this.index[k].mute();
            }
        }

        unmuteAll() {
            for (let k in this.index) {
                this.index[k].unmute();
            }
        }

        setVolumeAll(volume) {
            for (let k in this.index) {
                this.index[k].setVolume(volume);
            }
        }

        initPlayers(callback) {
            const self = this;
            window.onYouTubeIframeAPIReady = function () {
                for (let k in self.index) {
                    if (self.index[k] instanceof YoutubeBackground) {
                        self.index[k].initYTPlayer();
                    }
                }
                if (callback) {
                    setTimeout(callback, 100);
                }
            };
            if (window.hasOwnProperty("YT") && window.YT.loaded) {
                window.onYouTubeIframeAPIReady();
            }
            window.onVimeoIframeAPIReady = function () {
                for (let k in self.index) {
                    if (self.index[k] instanceof VimeoBackground) {
                        self.index[k].initVimeoPlayer();
                    }
                }
                if (callback) {
                    setTimeout(callback, 100);
                }
            };
            if (window.hasOwnProperty("Vimeo") && window.Vimeo.hasOwnProperty("Player")) {
                window.onVimeoIframeAPIReady();
            }
        }
    };

    // src/main.js
    if (typeof jQuery == "function") {
        (function ($) {
            $.fn.youtube_background = function (params) {
                const $this = $(this);
                if (window.hasOwnProperty("VIDEO_BACKGROUNDS")) {
                    window.VIDEO_BACKGROUNDS.add($this, params);
                    return $this;
                }
                window.VIDEO_BACKGROUNDS = new VideoBackgrounds(this, params);
                return $this;
            };
        })(jQuery);
    }
    window.VideoBackgrounds = VideoBackgrounds;
})();
//# sourceMappingURL=jquery.youtube-background.js.map
;
var version={js:"18-9-2024 23:56",git:"0"};$(function(){function e(e,a){null!=Oe&&(clearTimeout(Oe),Oe=null),null!=je&&(clearTimeout(je),je=null),0==Be?je=setTimeout(function(){$(e).parent().find(".cd-dropdown").addClass("dropdown-is-active"),$(e).parent().find(".cd-dropdown-trigger").addClass("dropdown-is-active"),je=null,Be=!0},a):(t(0),setTimeout(function(){$(e).parent().find(".cd-dropdown").addClass("dropdown-is-active"),$(e).parent().find(".cd-dropdown-trigger").addClass("dropdown-is-active"),je=null,Be=!0}))}function t(e){if(null==Oe)return null!=je?(clearTimeout(je),void(je=null)):void(Oe=setTimeout(function(){$(".dropdown-is-active").removeClass("dropdown-is-active"),Be=!1,Oe=null},e))}function a(){const e="sb05-swiftsearch-overlay",t=document.getElementById(e);t&&(t.style.display="none")}function o(){const e="sb05-swiftsearch-overlay",t=document.getElementById(e);t&&(t.style.display="block")}function n(){$("#newheader ul.nav-l1 .open").removeClass("open")}function s(e){var t=!e.find(".cd-dropdown-v1").hasClass("dropdown-is-active-v1");e.find(".cd-dropdown-v1").toggleClass("dropdown-is-active-v1",t),e.find(".cd-dropdown-trigger-v1").toggleClass("dropdown-is-active-v1",t),Fe=!0;setTimeout(function(){Fe=!1},15);t?(Ge&&Ge[0]!==e[0]&&s(Ge),Ge=e):(e.find(".cd-dropdown-v1").one("webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend",function(){e.find(".has-children ul").addClass("is-hidden"),e.find(".move-out").removeClass("move-out"),e.find(".is-active").removeClass("is-active")}),Ge=null)}function r(e,t,a){var i='<div class="hero-modal" aria-hidden="true"><button><span class="icomoon-Close"></span></button><div class="flexbox--center"><iframe width="'+t+'" height="'+a+'" src="'+e+'?autoplay=1" frameborder="0" allowfullscreen></iframe></div></div>';$("body").prepend(i),TweenMax.fromTo($(".hero-modal"),.5,{css:{opacity:0}},{css:{opacity:1}}),$(document).keyup(function(e){27==e.keyCode&&l()}),$(".hero-modal button").on("click",l)}function l(){TweenMax.fromTo($(".hero-modal"),.5,{css:{scale:1}},{css:{scale:1,opacity:0},onComplete:function(){$(".hero-modal button").unbind("click"),$(".hero-modal").remove(),$(document).unbind("keyup")}})}function c(e){var t=e?e+' iframe[src*="youtube.com"], '+e+' iframe[src*="vimeo.com"]':'iframe[src*="youtube.com"], iframe[src*="vimeo.com"]';$(t).each(function(e){$(this).attr("data-src",$(this).attr("src")),$(this).attr("data-aspect",$(this).attr("width")/$(this).attr("height")),"FIGURE"===$(this).parent().prop("nodeName")&&($parent=$(this).parent(),$parent.addClass("video"),$parent.prepend('<div class="vid-img-placeholder"><div class="icon-svg-playbutton"></div></div>'),$parent.find("img").appendTo(".vid-img-placeholder",$parent))}),$("figure.video").on("click",function(){$el=$(this).find("iframe"),r($el.attr("data-src"),$el.attr("width"),$el.attr("height"))}),$(".play.video").each(function(){$parent=$(this).parent(),$target=$(this),$parent.is("a")&&$parent.on("click",function(e){e.preventDefault(),$target.trigger("click")})}),$('.play.video, li[class*="tile--1"] .video').on("click",function(){$el=$(this).find("iframe"),r($el.attr("data-src"),$el.attr("width"),$el.attr("height"))})}function d(e,t,a){if(a){var i=new Date;i.setTime(i.getTime()+24*a*60*60*1e3);var o="; expires="+i.toGMTString()}else var o="";document.cookie=e+"="+t+o+"; path=/"}function u(e){for(var t=e+"=",a=document.cookie.split(";"),i=0;i<a.length;i++){for(var o=a[i];" "==o.charAt(0);)o=o.substring(1,o.length);if(0==o.indexOf(t))return o.substring(t.length,o.length)}return null}function p(e,t,a){Ke=!0,$carouselNav=e.find(".carousel-nav"),$carouselImageSlider=e.find(".carousel-images"),$carouselContentSlider=e.find(".carousel-content"),$carouselContainer=e.find(".carousel-container"),t?(a++,TweenMax.to($carouselImageSlider,.6,{left:"-=100%",ease:Power1.easeInOut})):(a--,TweenMax.to($carouselImageSlider,.6,{left:"+=100%",ease:Power1.easeInOut})),0==$carouselImageSlider.find("div").eq(a-1).find("img").length?$carouselContainer.find(".carousel-media").addClass("inactive"):$carouselContainer.find(".carousel-media").removeClass("inactive"),$carouselContentSlider.children("div").css({opacity:0}),$carouselContentSlider.children("div").removeClass("active"),$carouselContentSlider.children("div").eq(a-1).addClass("active"),TweenMax.fromTo($carouselContentSlider.children("div").eq(a-1),.6,{top:"+=10%",ease:Power1.easeInOut},{top:"-=10%",opacity:1,ease:Power1.easeInOut}),TweenMax.fromTo($carouselNav.find(".line"),.6,{width:0},{width:30,onComplete:function(){Ke=!1}}),e.find(".currSlide").html(a)}function h(){for(var e,t=[],a=window.location.href.slice(window.location.href.indexOf("?")+1).split("&"),i=0;i<a.length;i++)e=a[i].split("="),t.push(e[0]),t[e[0]]=e[1];return t}function m(e){for(var t=window.location,a=t.href.indexOf("?")>0?t.href.slice(t.href.indexOf("?")+1).split("&"):"",i=[],o=0,n=a.length;o<n;o++)a[o].indexOf("firsttime")>=0||a[o].indexOf("journey")>=0||i.push(a[o]);return location.origin+location.pathname+"?"+i.join("&")}function f(){$(".cb15 ul.list-category li").each(function(e){$(this).attr("data-url")&&""!=$(this).attr("data-url")?($(this).find('span[class*="icon-svg-accord"]').addClass("hide--me"),$(this).find("button").append('<span class="link icomoon-ArrowRight"></span>'),$(this).find("button span.link").hide().show(0)):$(this).find('span[class*="icon-svg-accord"].hide--me').removeClass("hide--me")})}function g(){var e=!1,t=document.getElementsByTagName("script"),a="https://display.ugc.bazaarvoice.com/static/canon-anz/en_AU/bvapi.js";for(i=0;i<t.length;i++)t[i].src==a&&(e=!0);e&&setTimeout(function(){var e='div[id*="BVRR"] .bv-cleanslate.bv-cv2-cleanslate .bv-core-container-40 .bv-content-secondary-ratings-value,.bv-cv2-cleanslate .bv-core-container-40 .bv-secondary-rating-summary-value,.bv-cv2-cleanslate .bv-core-container-40 .bv-secondary-slider-summary-value,.bv-cv2-cleanslate .bv-core-container-40 .bv-content-slider-value';$(e).each(function(e){var t=$(this).attr("style");$(this).attr("style",t+" background-color:#3cb896 !important;")})},1e3)}function b(e){var t=(document.getElementById("image-gallery-placeholder"),"");$("#gallery-image-list").empty(),e&&"View all destinations"!==e||(e=""),$.each(et,function(a,i){e&&e!=i.title||(t+='<li class="item posn--rel" style="background-image: url('+i.image+')">',t+='<div class="posn--abs hover information">',t+='<p class="information-heading" id="information-heading">'+i.title+"</p>",t+='<p class="information-subtitle-1">'+i.subtitle1+"</p>",t+="<p>"+i.subtitle2+"</p>",t+="<p>"+i.subtitle3+"</p>",t+='<p class="learn-more">Learn more<span id="learn-more-icon" class="icomoon-LongArrowRight icon"></span></p>',t+="</div>",t+="</li>")}),$(".img__gallery .gallery .items").append(t)}function y(e){var t=$("#filter-destination option:selected").text();$("#filter-destination option:disabled").remove(),b(t)}function v(e,t){var a=Number(t)+1,i="";return e.litebox&&(i+='<div class="left cols--1-2">',i+='<div class="upper flexbox">',i+='<div class="goleft posn--rel">',1!==a&&(i+='<button id="litebbox-previous" class="posn--abs goleft-btn"></button>'),i+="</div>",i+='<div class="middle">',i+='<div class="img-placeholder" style="background-image: url('+e.litebox[t].image+')"></div>',i+="</div>",10!==a&&(i+='<div class="goright posn--rel">',i+='<button id="litebbox-next-mobile" class="posn--abs goright-btn mobile"></button>',i+="</div>"),i+="</div>",i+='<div class="lower flexbox lower-desktop">',i+='<div class="credit">'+e.litebox[t].photoBy+"</div>",i+='<div class="count">'+a+'/10<span class="redline"></span></div>',i+="</div>",i+="</div>",i+='<div class="right cols--1-2 flexbox posn--rel">',i+='<div class="lower flexbox lower-mobile">',i+='<div class="credit">'+e.litebox[t].photoBy+"</div>",i+='<div class="count">'+a+'/10<span class="redline"></span></div>',i+="</div>",i+='<h2 class="mobile-litebox-title">'+e.litebox[t].title+"</h2>",i+="<div>"+e.litebox[t].description+"</div>",i+='<div class="head posn--abs">',i+='<h2 class="pos--abs"><span class="redline"></span>'+e.litebox[t].title+"</h2>",i+="</div>",i+='<div class="download posn--abs">',i+='<a href="'+e.brochure+'" class="link btn--2">Download full itinerary</a>',i+="</div>",i+="</div>",10!==a&&(i+='<div class="goright posn--rel">',i+='<button id="litebbox-next-desktop" class="posn--abs goright-btn mobile"></button>',i+="</div>")),i}function w(e,t){$("#litebox-content").find("div:first").remove(),$("#litebox-content").find("div:first").remove(),$("#litebox-content").find("div:first").remove(),$("#litebox-content").append(e),$(".goright").off("click"),$(".goright").on("click","button",function(){E(t)}),$(".goleft").off("click"),$(".goleft").on("click","button",function(){C(t)})}function S(e){var t;t="learn-more-icon"==e.target.id?$(e.target).parent().parent().find("#information-heading"):$(e.target).parent().find("#information-heading");var a=t[0].textContent;$.each(et,function(e,t){if(a==t.title){var i=v(t,0);w(i,a)}})}function k(){$("#filter-destination").empty();var e=$(".img__gallery").innerWidth()||window.innerWidth;e<=768?($("#filter-destination").append("<option selected disabled>View Destination</option>"),$("#filter-destination").append('<option value="">View all destinations</option>')):$("#filter-destination").append('<option value=""></option>'),$.each(Ze,function(e,t){$("#filter-destination").append("<option value="+e+">"+t.destination+"</option>")})}function E(e){$.each(et,function(t,a){if(e!=a.title);else{var i=$(".count")[0].textContent,o="10/10"==i?10:i.substring(0,1);if(o<10){var n=v(a,o);w(n,e)}}})}function C(e){$.each(et,function(t,a){if(e!=a.title);else{var i=$(".count")[0].textContent,o="10/10"==i?10:i.substring(0,1);if(o>1){var n=Number(o)-2,s=v(a,n);w(s,e)}}})}function I(){$.each(tt,function(e,t){$("#camera-models-mobile").append("<tr><td>"+t.category+"</td><td>"+t.product+"</td><td>"+t.entries+"</tr>"),$("#camera-models-desktop").append("<tr><td>"+t.category+"</td><td>"+t.product+"</td><td>"+t.entries+"</tr>")})}function P(){k(),b(),I(),window.addEventListener("resize",function(){k()},!1),window.addEventListener("orientationchange",function(){k()},!1),$(".dpicker").datepicker({showOn:"both",buttonImage:"/images/svg/icon-datepicker.svg",buttonImageOnly:!0,buttonText:"Select date",dateFormat:"dd/mm/yy",maxDate:new Date(2019,0,6),minDate:new Date(2018,9,15)})}function N(){var e=$("#product-select option:selected").text(),t="<table><tbody>";t+="<tr>",t+="<th>Product Categories</th>",t+="<th>Product</th>",t+="<th>Competition Entries</th>",t+="</tr>",$.each(tt,function(a,i){e==i.category&&(t+="<tr>",t+="<td>"+i.category+"</th>",t+="<td>"+i.product+"</th>",t+="<td>"+i.entries+"</th>",t+="</tr>")}),t+="</tbody></table>",$("#product-table").find("table:first").remove(),$("#product-table").append(t)}function T(){$('div[class*="tiled--"] ul').each(function(e,t){$ul=$(this),$top=-1,$row=0,$ul.find("li").each(function(e,t){$li=$(this),$li.position().top>$top?($row++,$top=$li.position().top,$li.addClass("margin--l0")):$li.removeClass("margin--l0")})}),$('div[class*="tiled--"] ul li').each(function(e,t){0==parseFloat($(this).css("margin-bottom"))&&$(this).css("margin-bottom",.0125*parseFloat($(this).parent().css("width")))})}function M(e,t,a,i,o,n,s,r,l){var c=function(){return e||""!==t?""!==e?'<div class="media-data"><iframe width="790" height="460" src="'+e+'" frameborder="0" allowfullscreen></iframe></div>':'<div class="media-data"><img src="'+t+'" alt=""></div>':""},d=function(){return""!==n?"header-colored "+n:""},u='<div class="hero-modal bg-white" aria-hidden="true"><div class="flexbox--center"><div class="modal-body centered--v-h"><button class="button"><span class="icomoon-Close"></span></button><div class="modal-header '+d()+'"><div class="author-date-data"><span>Submitted by '+a+" "+i+" , "+o+'</span></div><h3 class="modal-title">'+r+'<div class="fb-likes"><div class="fb-like" data-href="'+s+'" data-layout="button_count" data-action="like" data-size="small" data-show-faces="true" data-share="false"></div></div></h3></div><div class="modal-content"><div class="description">'+l+"</div>"+c()+"</div></div></div></div>";$("html").addClass("f-open"),$("body").prepend(u),TweenMax.fromTo($(".hero-modal"),.5,{css:{opacity:0}},{css:{opacity:1}}),$(document).keyup(function(e){27==e.keyCode&&x()}),$(".hero-modal button").on("click",x),$(".hero-modal").on("click",function(){event.target==$(".hero-modal").get(0)&&x()})}function x(){$("html").removeClass("f-open"),TweenMax.fromTo($(".hero-modal"),.5,{css:{scale:1}},{css:{scale:1,opacity:0},onComplete:function(){$(".hero-modal button").unbind("click"),$(".hero-modal").remove(),$(document).unbind("keyup")}})}function L(){function e(){$scope.find(".link3").on("click",function(e){e.preventDefault()}),$scope.find(".link2").on("click",function(e){e.preventDefault()}),$scope.find(".delete").on("click",function(e){e.preventDefault(),$("body").append($modal),TweenMax.fromTo($("body .mc-modal"),.5,{css:{opacity:0}},{css:{opacity:1}}),$("body .mc-modal .cancel").on("click",function(){t()}),$("body .mc-modal .remove").on("click",function(){t()})})}function t(){TweenMax.fromTo($(".hero-modal"),.5,{css:{scale:1}},{css:{scale:1,opacity:0},onComplete:function(){$("body .mc-modal .remove").off("click"),$("body .mc-modal .cancel").off("click"),$("body .mc-modal").remove()}})}return $scope=$(".tile--162"),$modal='<div class="hero-modal mc-modal" aria-hidden="true"> <div class="flexbox--center"> <div class="content"> <h2 class="heading">Are you sure your want to remove this event?</h2> <p> <span class="btn--3 cancel">Cancel</span> <span class="btn--1 remove">Yes, remove event</span> </p></div></div></div>',{_init:function(){e()}}}function A(){function e(){a.find(".tabs ul li:nth-child("+i+")").addClass("active"),a.find(".content .tab"+i).addClass("active"),a.find(".tabs ul").on("click keyup","li",function(e){return"keyup"===e.type&&13!=e.keyCode?null:($(this).siblings().removeClass("active").end().addClass("active"),void t($(this).index()+1))}),a.find(".category ul.os").on("click","li",function(e){$(this).siblings().removeClass("active").end().addClass("active")}),a.find(".search-container input").on("keyup",function(e){9===e.which&&console.log(e)}),a.find(".tab-container .items").each(function(){var e=$(this).find("li").length;if(e>4){for(var t="",a=1,i=parseInt(e/4)+(e%4>0?2:1);a<i;a++)t+=1===a?'<li class="active" tab-index="0" role="button">'+a+"</li>":'<li tab-index="0" role="button">'+a+"</li>";$(this).parent().append('<div class="pagination"><ul>'+t+"</ul></div>")}}),a.find(".pagination").each(function(e){$(this).parents(".tab-container").find("ul.items li").addClass("hide"),$(this).parents(".tab-container").find("ul.items li:nth-child(-n+4)").removeClass("hide")}),a.find(".pagination ul").on("click","li",function(e){var t=$(this);$(this).siblings().removeClass("active").end().addClass("active");var a=($(this).parents(".tab-container").find("ul.items li").addClass("hide"),1*t.index()+1);a=4*(a-1)+1;for(var i=a;i<a+4;i++)$(this).parents(".tab-container").find("ul.items li:nth-child("+i+")").removeClass("hide")}),a.find(".search-open").on("click",function(e){$(this).prev().css("display","grid"),$(this).parent(".category").addClass("s-open"),$(this).prev().find("input").focus()}),a.find(".search-container button.icomoon-Close").on("click",function(){$(this).parents(".category").removeClass("s-open")}),a.find(".category.mobile button.open").on("click touchstart",function(){$(this).next().addClass("active")}),a.find(".category.mobile button.close").on("click",function(e){$button=$(this),TweenMax.to($(this).parents(".modal"),1,{css:{left:"-100%"},ease:Power4.easeOut,onComplete:function(e){e.removeClass("active"),TweenMax.set(e,{clearProps:"all"})},onCompleteParams:[$(this).parents(".modal")]})})}function t(e){a.find('.content div[class*="tab"].active').removeClass("active"),a.find(".content .tab"+e).addClass("active")}var a=$(".cf05v2"),i=h().tab||"1";return{_init:function(t){e()}}}function _(){function e(){t.each(function(){var e=$(this).find(".expand-text").html().slice(0,200)+" ...";$(this).find(".expand-text").addClass("long hide--me").after('<p class="desc expand-text clearfix short">'+e+'</p><a href="#" class="show-more">Show more +</a><a href="#" class="show-less hide--me">Show less -</a>'),$(this).find(".show-more").on("click",function(){event.preventDefault(),$(this).parent().find(".long").removeClass("hide--me"),$(this).parent().find(".short").addClass("hide--me"),$(this).parent().find(".show-more").addClass("hide--me"),$(this).parent().find(".show-less").removeClass("hide--me")}),$(this).find(".show-less").on("click",function(){event.preventDefault(),$(this).parent().find(".short").removeClass("hide--me"),$(this).parent().find(".long").addClass("hide--me"),$(this).parent().find(".show-less").addClass("hide--me"),$(this).parent().find(".show-more").removeClass("hide--me")})})}var t=$(".tile--106");return{_init:function(t){e()}}}function D(){function e(){t(),$(window).resize(function(){t()})}function t(){var e=2e4;n.width()<=700&&(e=18e5/70,n.find(".heading").off("click"),n.find(".heading").on("click",".cols--1-2",function(){var e=.05;1===$(this).index()?(n.find(".layouts .layout-front .layout--1200 > div:nth-child(1) li").each(function(){TweenMax.fromTo($(this),l,{css:{opacity:1}},{css:{opacity:0},delay:e}),e+=r}),e=2*r,n.find(".layouts .layout-front .layout--1200 > div:nth-child(2) li").each(function(){TweenMax.fromTo($(this),l,{css:{opacity:0,y:200*e}},{css:{opacity:1,y:0},delay:e}),e+=r})):(n.find(".layouts .layout-front .layout--1200 > div:nth-child(2) li").each(function(){TweenMax.fromTo($(this),l,{css:{opacity:1}},{css:{opacity:0},delay:e}),e+=r}),e=2*r,n.find(".layouts .layout-front .layout--1200 > div:nth-child(1) li").each(function(){TweenMax.fromTo($(this),l,{css:{opacity:0,y:200*e}},{css:{opacity:1,y:0},delay:e}),e+=r})),n.find(".heading .active").removeClass("active"),$(this).addClass("active")})),n.find(".layout-front ul li").each(function(t,n){a=new Date("2038-01-01T"+s+":00"),i=new Date("2038-01-01T"+$(this).attr("data-start")),o=new Date("2038-01-01T"+$(this).attr("data-end")),$(this).css("top",(i-a)/e+1),$(this).css("height",(o-i)/e-3)})}var a,i,o,n=$(".cla-s"),s=n.find(".layout-back ul li:first-child").attr("data-start"),r=.25,l=.15;return{_init:function(t){e()}}}function R(){function e(){var e=document.createElement("script");e.setAttribute("src","https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.10/jquery.mask.min.js"),document.body.appendChild(e)}return{_init:function(){e()}}}function j(){function e(){c=String($scope.attr("data-token"))||"4d6f2f6618da47f7801fb957dd197e35",d=$scope.attr("data-api")||"https://api.api.ai/v1/",r("https://cdnjs.cloudflare.com/ajax/libs/jquery-autocomplete/1.0.7/jquery.auto-complete.min.js",l),$scope.find("section .content button.search").on("click",function(){$scope.find("section.start input").trigger(jQuery.Event("keydown",{which:$.ui.keyCode.ENTER}))}),$scope.find("section .content button.clear").on("click",function(){$scope.find("section.start input").val("")}),$scope.find("section.start input").on("keypress",function(e){13==e.which&&$(this).val().length<3&&$scope.find("section.start input").val("")}),$scope.find("section.start input").val(""),t("hello")}function t(e){$.ajax({type:"POST",url:d+"query?v=20150910",contentType:"application/json; charset=utf-8",dataType:"json",headers:{Authorization:"Bearer "+c},data:JSON.stringify({query:text,lang:"en",sessionId:u}),success:function(e){return p&&console.log("Response",e),e.status&&"200"===String(e.status.code)&&"success"===String(e.status.errorType)&&a(e),null},error:function(){p&&console.log("Lets do something else")}})}function a(e){p&&console.log("Payload: checking"),$payload=o(e.result.fulfillment.messages,"payload"),$payload?(p&&console.log("Payload: ok",$payload),"start"==$payload.content.type&&n($payload.content)):p&&console.log("Payload: missing. I'm outa here")}function o(e,t){var a=null;return Object.keys(e).forEach(function(i){if("object"==typeof e[i][t])return a=e[i][t],null}),a}function n(e){TweenMax.to($scope,.35,{css:{opacity:1}}),p&&console.log("Start: lets created the start section",e),$slide=$scope.find("section.start"),TweenMax.fromTo($slide.find(".content"),.35,{css:{"margin-top":250,opacity:1}},{css:{"margin-top":0,opacity:1}}),e.heading&&$slide.find(".heading").text(e.heading),e.input?(p&&console.log(e.input),$slide.find("input").attr("placeholder",e.input.placeholder),e.input.autocomplete&&s($slide.find("input"),e.input.autocomplete)):$slide.find("input").css("display","none")}function s(e,t){p&&console.log("Start: config autocomplete",e,t),e.autoComplete({minChars:1,source:function(e,a){e=e.toLowerCase();var o=[];for(i=0;i<t.length;i++)~t[i].toLowerCase().indexOf(e)&&o.push(t[i]);a(o)}})}function r(e,t){var a=document.getElementsByTagName("head")[0],i=document.createElement("script");i.src=e,i.type="text/javascript",i.onload=t,i.onreadystatechange=function(){"complete"==this.readyState&&t()},a.appendChild(i)}function l(){return null}$scope=$(".how-to-video");var c,d,u=parseInt(1e6*Math.random()),p=!0;return{_init:function(){e()}}}function O(){function e(){if($scope.find("section.start input").attr("data-autocomplete")&&o("https://cdnjs.cloudflare.com/ajax/libs/jquery-autocomplete/1.0.7/jquery.auto-complete.min.js",n),$scope.find("section .content button.search").on("click",function(){$scope.find("section.start input").trigger(jQuery.Event("keydown",{which:$.ui.keyCode.ENTER}))}),$scope.find("section .content button.clear").on("click",function(){$scope.find("section.start input").val("")}),$scope.find("section.start input").on("keydown",function(e){13==e.which&&($(this).val().length<1?$scope.find("section.start input").val(""):($(".autocomplete-suggestions").css("display","none"),$(this).attr("readonly","readonly"),$(this).attr("disabled","true"),setTimeout(function(){$scope.find("section.start input").blur().removeAttr("readonly"),$scope.find("section.start input").blur().removeAttr("disabled")},100),a($(this).val().toLowerCase())))}),$scope.find("section.start input").val(""),$scope.find("section[data-id]").each(function(){$(this).attr("data-id").length>0&&($el=$(this).attr("data-id").split("/"));for(var e=0;e<$el.length;e++)$obj[$el[e]]=$(this)}),$scope.find("section button.option").on("click",function(){a($(this).attr("data-ref"))}),$scope.find("section .goback").on("click",function(){var e=$journeyArr.join(".");window.setTimeout(function(){$obj[e].css("display","none"),$scope.find("section iframe").attr("src","")},830);$journeyArr=$journeyArr.slice(0,-1),t()}),""!==$deeplink){$scope.find("section.start input").val($deeplink);var e=$.Event("keydown",{which:13});$scope.find("section.start input").trigger(e)}}function t(){var e=document.getElementById("howtovideo");e.style.display="none",e.offsetHeight,e.style.display="block";var t=$journeyArr.join(".");""===t?$scope.find(".scroller").css("transform","translate3d(0px, -"+$scope.find("section.start").position().top+"px, 0px)"):($obj[t].css("display","block"),$scope.find(".scroller").css("transform","translate3d(0px, -"+$obj[t].position().top+"px, 0px)"),$obj[t].find("iframe").length>0&&$obj[t].find("iframe").attr("src",$obj[t].find("iframe").attr("data-src")))}function a(e){$journeyArr.push(e);var a=$journeyArr.join(".");if($obj[a]){t();var i=$scope.find("section.start input").val();$scope.find("span.user-camera").text(i)}else{$journeyArr=$journeyArr.slice(0,-1);var o,a=$journeyArr.join(".");""===a&&$scope.find("section.start .user-error").length>0?o=$scope.find("section.start"):$obj[a].find(".user-error").length>0&&(o=$obj[a]),o&&($err=o.find(".user-error"),TweenMax.fromTo($err.closest(".content").find("h2,.search,.bottom"),.2,{css:{opacity:1}},{css:{opacity:0,display:"none"}}),TweenMax.fromTo($err,.2,{css:{opacity:0}},{css:{opacity:1,autoAlpha:1,display:"block"},delay:.25}),$err.find("button").off("click").on("click",function(){TweenMax.fromTo($err,.2,{css:{opacity:1}},{css:{opacity:0,autoAlpha:0,display:"none"}}),TweenMax.fromTo($err.closest(".content").find("h2,.search,.bottom"),.2,{css:{opacity:0}},{css:{opacity:1,display:"block"},delay:.2})}))}}function o(e,t){var a=document.getElementsByTagName("head")[0],i=document.createElement("script");i.src=e,i.type="text/javascript",i.onload=t,i.onreadystatechange=function(){"complete"==this.readyState&&t()},a.appendChild(i)}function n(){$scope.find("section.start input").autoComplete({minChars:1,source:function(e,t){e=e.toLowerCase();var a=$scope.find("section.start input").attr("data-autocomplete").split(","),o=[];for(i=0;i<a.length;i++)~a[i].toLowerCase().indexOf(e)&&o.push(a[i]);console.log(o),t(o)}})}return $scope=$(".how-to-video-v1"),$journey="",$journeyArr=[],$obj={},$previous=$scope.find("section.start"),$current=$scope.find("section.start"),$height=640,$currentHeight=0,$deeplink=h().model||"",{_init:function(){e()}}}function B(){function e(){$(".mcb21").find(".loader").removeClass("hide--me"),N?t():U("https://www.gstatic.com/firebasejs/4.1.2/firebase.js",t)}function t(){firebase.initializeApp(T),N=firebase.database(),E="iradvc",console.log(k,E,C);var e=N.ref(k+"/support/help/"+E);e.once("value",a,function(){console.error("Model/device support help not found")})}function a(e){v=y(C),console.log("series:",v),M.nodes=e.val().nodes,Object.keys(M.nodes).forEach(function(e){o(e,M.nodes[e])}),$(".mcb21").append(I),r(),P.push(Object.keys(M.nodes)[0]),$(".mcb21").find(".loader").addClass("hide--me"),m(),h().solution?d(h().solution):"",U("https://cdnjs.cloudflare.com/ajax/libs/jquery-autocomplete/1.0.7/jquery.auto-complete.min.js",g)}function o(e,t){if(t.view&&t.type){var a=M.theme[t.type];w=t.solution?t.solution:"",e.indexOf("imagequality")>0,"end"===t.type?(w=t.solution?t.solution:"",a=a.replace("dmodel",e).replace("dtype",t.type).replace("xxx",n(t)).replace("dsol",w)):a=a.replace("dmodel",e).replace("dtype",t.type).replace("xxx",n(t)),I+=a}else console.warn("Missing","view:",t.view," type",t.type)}function n(e){var t="";return Object.keys(e.view).forEach(function(a){if(type=e.view[a].type,mdl=e.view[a].model?e.view[a].model:"",mdl&&v){var i=mdl.split("|"),o="all"===mdl;if(!o)for(var n=0;n<i.length;n++)s(v,i[n])&&(o=!0);if(e.view[a].except&&o){i=e.view[a].except.split("|");for(var n=0;n<i.length;n++)s(v,i[n])&&(o=!1)}if(!o)return null}if(e.view[a].solution&&(w=e.view[a].solution),"text"===type&&(e.view[a].h2&&(t+="<h2>"+e.view[a].h2+"</h2>"),e.view[a].p))if("object"==typeof e.view[a].p){var r=e.view[a].p;Object.keys(r).forEach(function(e){t+="<p>"+r[e]+"</p>"})}else"string"==typeof e.view[a].p&&(t+="<p>"+e.view[a].p+"</p>");if("list"===type&&(e.view[a].ul||e.view[a].ol)){var l=e.view[a].ul?"ul":"ol",c=e.view[a]["class"]?" "+String(e.view[a]["class"]):"",d=' data-length="'+Object.keys(e.view[a][l]).length+'"';t+="<"+l+' class="links'+c+'"'+d+">",Object.keys(e.view[a][l]).forEach(function(i){d++;var o="";e.view[a][l][i].img&&(o='<img src="'+e.view[a][l][i].img+'">'),t+=e.view[a][l][i].link?'<li data-link="'+e.view[a][l][i].link+'">'+e.view[a][l][i].text+o+"</li>":"<li>"+(e.view[a][l][i].text?e.view[a][l][i].text:"")+o+"</li>"}),t+="</"+l+">"}if("img"===type&&("object"==typeof e.view[a].img?Object.keys(e.view[a].img).forEach(function(i){t+='<img src="'+e.view[a].img[i]+'" >'}):t+='<img src="'+e.view[a].img+'" >'),"pdf"===type&&(t+='<a href="'+e.view[a].link+'" target="_blank">'+e.view[a].text+"</a>"),"button"===type){var c=e.view[a]["class"]?" "+String(e.view[a]["class"]):"",u="?sn="+(h().sn||"");t+=e.view[a].link?'<a href="'+e.view[a].link+u+'" class="btn'+c+'">'+e.view[a].text+"</a>":'<button class="btn'+c+'">'+e.view[a].text+"</button>"}if("line"===type){var c=e.view[a]["class"]?" "+String(e.view[a]["class"]):"";t+='<div class="line'+c+'"></div>'}"input"===type&&(t+='<div class="user-input"><div class="input-container flexbox"><input type="text" placeholder="e.g download print driver"><button class="speak icon-svg-mic"></button></div><div class="error">I\'m not sure what you mean. Try again or choose an option above.</div></div>'),"skip"===type&&(t+='<input type="hidden" name="skip" class="skip" value="'+e.view[a].skipto+'">')}),t}function s(e,t){return t.indexOf("*")===-1&&e===t||(t.indexOf("*")!==-1||e===t)&&(e.length===t.length&&new RegExp("^"+t.split("*").join(".*")+"$").test(e))}function r(){$(".mcb21").find("section input").on("keydown",function(e){$(".mcb21").find("section.start .user-input .error").removeClass("active"),$(".autocomplete-suggestions").addClass("mcb21-ac"),console.log("clicked",e),13==e.which&&($(this).val().length>2||$(this).val().length>=$(this).attr("data-min"))&&(x=$(this).val().toLowerCase(),f(x))}),$(".mcb21").find("section ul").on("click","li[data-link]",function(){u($(this).attr("data-link"))}),$(".mcb21").find("section button[data-ref]").on("click",function(){findPath(uKey($(this)),$(this).attr("data-ref"))}),$(".mcb21").find("section .goback").on("click",function(){for(var e=$(this).closest("section"),t=P.length-1;t>=0&&P[t]!==e.attr("data-model");t--)$(".mcb21").find('section.active[data-model="'+P[t]+'"]').removeClass("active"),P=P.slice(0,-1);window.setTimeout(function(){e.removeClass("active"),$(".mcb21").find("section iframe").attr("src","")},550);P=P.slice(0,-1),m(e)}),$(".mcb21").find("section.start .input-container .speak").on("click",function(){$(this).toggleClass("inactive"),$(".mcb21").find("section.start .input-container .speak.inactive")?l():c()})}function l(){S=new webkitSpeechRecognition,S.onstart=function(e){},S.onresult=function(e){for(var t="",a=e.resultIndex;a<e.results.length;++a)t+=e.results[a][0].transcript;if(t){$(".mcb21").find("section.start .input-container input").val(t),$(".mcb21").find("section.start .input-container .speak.inactive").removeClass("inactive");var i=jQuery.Event("keydown");i.which=13,i.keyCode=13,$(".mcb21").find("section.start .input-container input").trigger(i)}c()},S.onend=function(){c()},S.lang="en-US",S.start()}function c(){S&&(S.stop(),S=null)}function d(e){for(var t=e.split("|"),a=1;a<t.length;a++){var i=t.slice(0,a+1);if(!M.nodes[i.join("|")])break;P.push(i.join("|")),$(".mcb21").find('section[data-model="'+i.join("|")+'"]').addClass("active")}var o=$(".mcb21").find('section[data-model="'+P.slice(-1)[0]+'"]');o.find("input.skip"),p(o),$("html, body").animate({scrollTop:o.offset().top-160},1e3)}function u(e){var t=e.split("|");if(P.length>0)for(var a=P.length-1;a>=0;a--)if(P[a].split("|").length===t.length){P.splice(a),$(".mcb21").find("section.active").each(function(){$.inArray($(this).attr("data-model"),P)===-1&&$(this).removeClass("active")});break}P.push(e),m()}function p(e){e&&e.find("img")&&e.find("img").each(function(){$this=$(this),$this.width()<1?$this.load(function(e,t){$(this).width()>$(this).parent().width()&&$(this).addClass("maximgw")}):$(this).width()>$(this).parent().width()&&$(this).addClass("maximgw")})}function m(e){var t=$(".mcb21").find('section[data-model="'+P.slice(-1)[0]+'"]');t.addClass("active"),p(t);var a=t.offset().top,i=$(window).scrollTop(),o=0,n="";if(P.length>1?(n=$(".mcb21").find('section[data-model="'+P.slice(-2)[0]+'"]').offset().top,e?o=t.attr("data-top")?t.attr("data-top"):i-(a-n):(o=a-n+i,t.attr("data-top",o))):1===P.length&&e?(n=e.offset().top,o=a+i-n):o=$(".mcb21").offset().top-160,o>0){var s=0;$(".mcb21").find("section.active").each(function(e,t){$(this).height()>s&&(s=$(this).height())})}o>0&&$("html, body").animate({scrollTop:o},550)}function f(e){rm=parseInt(1e6*Math.random()),$.ajax({type:"POST",url:A+"query?v=20150910",contentType:"application/json; charset=utf-8",dataType:"json",headers:{Authorization:"Bearer "+L},data:JSON.stringify({query:e,lang:"en",sessionId:rm}),success:function(e){if(e.status&&"200"===String(e.status.code)&&"success"===String(e.status.errorType))if("input.unknown"===e.result.action&&"Default Fallback Intent"===e.result.metadata.intentName)$(".mcb21").find("section.start .user-input .error").addClass("active");else if(e.result&&e.result.fulfillment&&e.result.fulfillment.messages&&e.result.fulfillment.messages[0])if("autocomplete"===e.result.metadata.intentName&&e.result.fulfillment.messages[1]&&e.result.fulfillment.messages[1].payload)b(e.result.fulfillment.messages[1].payload.responses);else{
var t=String(e.result.fulfillment.messages[0].speech).split("|");t.length>0?d(t.join("|")):$(".mcb21").find("section.start .user-input .error").addClass("active")}else $(".mcb21").find("section.start .user-input").css("display","none");else $(".mcb21").find("section.start .user-input").css("display","none");return null},error:function(){$(".mcb21").find("section.start .user-input").css("display","none")}})}function g(e){f("autocomplete");var t=h().query?String(decodeURIComponent(h().query)).toLowerCase():"";""!==t&&f(t)}function b(e){$(".mcb21 section.start input").autoComplete({minChars:1,source:function(t,a){t=t.toLowerCase();var o=e,n=[];for(i=0;i<o.length;i++)~o[i].toLowerCase().indexOf(t)&&n.push(o[i]);a(n)}})}function y(e){var t=[],e=decodeURIComponent(String(e).toLowerCase()).replace(/\s+/g,"");return t.push("ir"),e.indexOf("adv")>=0?t.push("adv"):t.push(""),e.indexOf("c")>=0?t.push("c"):t.push(""),t.push(e.replace(/\D+/g,"")),t.join("")}$(".mcb21");var v,w,S,k="",E="",C="",I="",P=[],N="",T=(window.webkitSpeechRecognition||window.mozSpeechRecognition||window.msSpeechRecognition||window.oSpeechRecognition||window.SpeechRecognition,{apiKey:"AIzaSyDy5IPiF0l5zsk-P9tE-EkhzQtAswj59II",authDomain:"wingman-d8e6a.firebaseapp.com",databaseURL:"https://wingman-d8e6a.firebaseio.com",projectId:"wingman-d8e6a",storageBucket:"wingman-d8e6a.appspot.com",messagingSenderId:"895379711633"}),M={theme:{start:'<section class="start active" data-model="dmodel" data-type="dtype">xxx</section>',journey:'<section class="journey" data-model="dmodel" data-type="dtype"><div class="top"><button class="goback">BACK</button></div><div class="middle">xxx</section>',end:'<section class="end" data-model="dmodel" data-type="dtype"><div class="top"><button class="goback">BACK</button></div><div class="middle"><div class="col1">Solution <span class="solution-num">dsol</span><span class="line"></span></div><div class="col2">xxx</div></div></section>',container:""},nodes:""},x="",L="f1a5a20d314242febe5459e6987b1957",A="https://api.api.ai/v1/";return{_init:function(e,t,a){init()},_deeplink:function(t,a){C=String(t).toLowerCase(),k=a,e()}}}function B(){function e(){$(".mcb21").find(".loader").removeClass("hide--me"),N?t():U("https://www.gstatic.com/firebasejs/4.1.2/firebase.js",t)}function t(){firebase.initializeApp(T),N=firebase.database(),E="iradvc",console.log(k,E,C);var e=N.ref(k+"/support/help/"+E);e.once("value",a,function(){console.error("Model/device support help not found")})}function a(e){v=y(C),console.log("series:",v),M.nodes=e.val().nodes,Object.keys(M.nodes).forEach(function(e){o(e,M.nodes[e])}),$(".mcb21").append(I),r(),P.push(Object.keys(M.nodes)[0]),$(".mcb21").find(".loader").addClass("hide--me"),m(),h().solution?d(h().solution):"",U("https://cdnjs.cloudflare.com/ajax/libs/jquery-autocomplete/1.0.7/jquery.auto-complete.min.js",g)}function o(e,t){if(t.view&&t.type){var a=M.theme[t.type];w=t.solution?t.solution:"",e.indexOf("imagequality")>0,"end"===t.type?(w=t.solution?t.solution:"",a=a.replace("dmodel",e).replace("dtype",t.type).replace("xxx",n(t)).replace("dsol",w)):a=a.replace("dmodel",e).replace("dtype",t.type).replace("xxx",n(t)),I+=a}else console.warn("Missing","view:",t.view," type",t.type)}function n(e){var t="";return Object.keys(e.view).forEach(function(a){if(type=e.view[a].type,mdl=e.view[a].model?e.view[a].model:"",mdl&&v){var i=mdl.split("|"),o="all"===mdl;if(!o)for(var n=0;n<i.length;n++)s(v,i[n])&&(o=!0);if(e.view[a].except&&o){i=e.view[a].except.split("|");for(var n=0;n<i.length;n++)s(v,i[n])&&(o=!1)}if(!o)return null}if(e.view[a].solution&&(w=e.view[a].solution),"text"===type&&(e.view[a].h2&&(t+="<h2>"+e.view[a].h2+"</h2>"),e.view[a].p))if("object"==typeof e.view[a].p){var r=e.view[a].p;Object.keys(r).forEach(function(e){t+="<p>"+r[e]+"</p>"})}else"string"==typeof e.view[a].p&&(t+="<p>"+e.view[a].p+"</p>");if("list"===type&&(e.view[a].ul||e.view[a].ol)){var l=e.view[a].ul?"ul":"ol",c=e.view[a]["class"]?" "+String(e.view[a]["class"]):"",d=' data-length="'+Object.keys(e.view[a][l]).length+'"';t+="<"+l+' class="links'+c+'"'+d+">",Object.keys(e.view[a][l]).forEach(function(i){d++;var o="";e.view[a][l][i].img&&(o='<img src="'+e.view[a][l][i].img+'">'),t+=e.view[a][l][i].link?'<li data-link="'+e.view[a][l][i].link+'">'+e.view[a][l][i].text+o+"</li>":"<li>"+(e.view[a][l][i].text?e.view[a][l][i].text:"")+o+"</li>"}),t+="</"+l+">"}if("img"===type&&("object"==typeof e.view[a].img?Object.keys(e.view[a].img).forEach(function(i){t+='<img src="'+e.view[a].img[i]+'" >'}):t+='<img src="'+e.view[a].img+'" >'),"pdf"===type&&(t+='<a href="'+e.view[a].link+'" target="_blank">'+e.view[a].text+"</a>"),"button"===type){var c=e.view[a]["class"]?" "+String(e.view[a]["class"]):"",u="?sn="+(h().sn||"");t+=e.view[a].link?'<a href="'+e.view[a].link+u+'" class="btn'+c+'">'+e.view[a].text+"</a>":'<button class="btn'+c+'">'+e.view[a].text+"</button>"}if("line"===type){var c=e.view[a]["class"]?" "+String(e.view[a]["class"]):"";t+='<div class="line'+c+'"></div>'}"input"===type&&(t+='<div class="user-input"><div class="input-container flexbox"><input type="text" placeholder="e.g download print driver"><button class="speak icon-svg-mic"></button></div><div class="error">I\'m not sure what you mean. Try again or choose an option above.</div></div>'),"skip"===type&&(t+='<input type="hidden" name="skip" class="skip" value="'+e.view[a].skipto+'">')}),t}function s(e,t){return t.indexOf("*")===-1&&e===t||(t.indexOf("*")!==-1||e===t)&&(e.length===t.length&&new RegExp("^"+t.split("*").join(".*")+"$").test(e))}function r(){$(".mcb21").find("section input").on("keydown",function(e){$(".mcb21").find("section.start .user-input .error").removeClass("active"),$(".autocomplete-suggestions").addClass("mcb21-ac"),console.log("clicked",e),13==e.which&&($(this).val().length>2||$(this).val().length>=$(this).attr("data-min"))&&(x=$(this).val().toLowerCase(),f(x))}),$(".mcb21").find("section ul").on("click","li[data-link]",function(){u($(this).attr("data-link"))}),$(".mcb21").find("section button[data-ref]").on("click",function(){findPath(uKey($(this)),$(this).attr("data-ref"))}),$(".mcb21").find("section .goback").on("click",function(){for(var e=$(this).closest("section"),t=P.length-1;t>=0&&P[t]!==e.attr("data-model");t--)$(".mcb21").find('section.active[data-model="'+P[t]+'"]').removeClass("active"),P=P.slice(0,-1);window.setTimeout(function(){e.removeClass("active"),$(".mcb21").find("section iframe").attr("src","")},550);P=P.slice(0,-1),m(e)}),$(".mcb21").find("section.start .input-container .speak").on("click",function(){$(this).toggleClass("inactive"),$(".mcb21").find("section.start .input-container .speak.inactive")?l():c()})}function l(){S=new webkitSpeechRecognition,S.onstart=function(e){},S.onresult=function(e){for(var t="",a=e.resultIndex;a<e.results.length;++a)t+=e.results[a][0].transcript;if(t){$(".mcb21").find("section.start .input-container input").val(t),$(".mcb21").find("section.start .input-container .speak.inactive").removeClass("inactive");var i=jQuery.Event("keydown");i.which=13,i.keyCode=13,$(".mcb21").find("section.start .input-container input").trigger(i)}c()},S.onend=function(){c()},S.lang="en-US",S.start()}function c(){S&&(S.stop(),S=null)}function d(e){for(var t=e.split("|"),a=1;a<t.length;a++){var i=t.slice(0,a+1);if(!M.nodes[i.join("|")])break;P.push(i.join("|")),$(".mcb21").find('section[data-model="'+i.join("|")+'"]').addClass("active")}var o=$(".mcb21").find('section[data-model="'+P.slice(-1)[0]+'"]');o.find("input.skip"),p(o),$("html, body").animate({scrollTop:o.offset().top-160},1e3)}function u(e){var t=e.split("|");if(P.length>0)for(var a=P.length-1;a>=0;a--)if(P[a].split("|").length===t.length){P.splice(a),$(".mcb21").find("section.active").each(function(){$.inArray($(this).attr("data-model"),P)===-1&&$(this).removeClass("active")});break}P.push(e),m()}function p(e){e&&e.find("img")&&e.find("img").each(function(){$this=$(this),$this.width()<1?$this.load(function(e,t){$(this).width()>$(this).parent().width()&&$(this).addClass("maximgw")}):$(this).width()>$(this).parent().width()&&$(this).addClass("maximgw")})}function m(e){var t=$(".mcb21").find('section[data-model="'+P.slice(-1)[0]+'"]');t.addClass("active"),p(t);var a=t.offset().top,i=$(window).scrollTop(),o=0,n="";if(P.length>1?(n=$(".mcb21").find('section[data-model="'+P.slice(-2)[0]+'"]').offset().top,e?o=t.attr("data-top")?t.attr("data-top"):i-(a-n):(o=a-n+i,t.attr("data-top",o))):1===P.length&&e?(n=e.offset().top,o=a+i-n):o=$(".mcb21").offset().top-160,o>0){var s=0;$(".mcb21").find("section.active").each(function(e,t){$(this).height()>s&&(s=$(this).height())})}o>0&&$("html, body").animate({scrollTop:o},550)}function f(e){rm=parseInt(1e6*Math.random()),$.ajax({type:"POST",url:A+"query?v=20150910",contentType:"application/json; charset=utf-8",dataType:"json",headers:{Authorization:"Bearer "+L},data:JSON.stringify({query:e,lang:"en",sessionId:rm}),success:function(e){if(e.status&&"200"===String(e.status.code)&&"success"===String(e.status.errorType))if("input.unknown"===e.result.action&&"Default Fallback Intent"===e.result.metadata.intentName)$(".mcb21").find("section.start .user-input .error").addClass("active");else if(e.result&&e.result.fulfillment&&e.result.fulfillment.messages&&e.result.fulfillment.messages[0])if("autocomplete"===e.result.metadata.intentName&&e.result.fulfillment.messages[1]&&e.result.fulfillment.messages[1].payload)b(e.result.fulfillment.messages[1].payload.responses);else{var t=String(e.result.fulfillment.messages[0].speech).split("|");t.length>0?d(t.join("|")):$(".mcb21").find("section.start .user-input .error").addClass("active")}else $(".mcb21").find("section.start .user-input").css("display","none");else $(".mcb21").find("section.start .user-input").css("display","none");return null},error:function(){$(".mcb21").find("section.start .user-input").css("display","none")}})}function g(e){f("autocomplete");var t=h().query?String(decodeURIComponent(h().query)).toLowerCase():"";""!==t&&f(t)}function b(e){$(".mcb21 section.start input").autoComplete({minChars:1,source:function(t,a){t=t.toLowerCase();var o=e,n=[];for(i=0;i<o.length;i++)~o[i].toLowerCase().indexOf(t)&&n.push(o[i]);a(n)}})}function y(e){var t=[],e=decodeURIComponent(String(e).toLowerCase()).replace(/\s+/g,"");return t.push("ir"),e.indexOf("adv")>=0?t.push("adv"):t.push(""),e.indexOf("c")>=0?t.push("c"):t.push(""),t.push(e.replace(/\D+/g,"")),t.join("")}$(".mcb21");var v,w,S,k="",E="",C="",I="",P=[],N="",T=(window.webkitSpeechRecognition||window.mozSpeechRecognition||window.msSpeechRecognition||window.oSpeechRecognition||window.SpeechRecognition,{apiKey:"AIzaSyDy5IPiF0l5zsk-P9tE-EkhzQtAswj59II",authDomain:"wingman-d8e6a.firebaseapp.com",databaseURL:"https://wingman-d8e6a.firebaseio.com",projectId:"wingman-d8e6a",storageBucket:"wingman-d8e6a.appspot.com",messagingSenderId:"895379711633"}),M={theme:{start:'<section class="start active" data-model="dmodel" data-type="dtype">xxx</section>',journey:'<section class="journey" data-model="dmodel" data-type="dtype"><div class="top"><button class="goback">BACK</button></div><div class="middle">xxx</section>',end:'<section class="end" data-model="dmodel" data-type="dtype"><div class="top"><button class="goback">BACK</button></div><div class="middle"><div class="col1">Solution <span class="solution-num">dsol</span><span class="line"></span></div><div class="col2">xxx</div></div></section>',container:""},nodes:""},x="",L="f1a5a20d314242febe5459e6987b1957",A="https://api.api.ai/v1/";return{_init:function(e,t,a){init()},_deeplink:function(t,a){C=String(t).toLowerCase(),k=a,e()}}}function G(){function e(){$(".mcb20").find(".self-help").on("click",function(e){if(e.preventDefault(),$(this).attr("data-model")&&!t){t=!0;var a=B();a._deeplink($(this).attr("data-model"),"mfd")}})}var t=($(".mcb20"),!1);return{_init:function(){e()}}}function U(e,t){var a=document.getElementsByTagName("head")[0],i=document.createElement("script");i.src=e,i.type="text/javascript",i.onload=t,i.onreadystatechange=function(){"complete"==this.readyState&&t()},a.appendChild(i)}function F(){function e(){$(".mc2--dash__nav .mystore .ddown").on("click",function(e){$(this).toggleClass("ddown-cross"),$(this).closest(".nav-content").toggleClass("ddown-show"),$(".mc2--dash__nav .left").trigger("scroll"),q()}),$(".mc2--dash__nav .left").scroll(function(){var e=$(".mc2--dash__nav .nav-content.ddown-show .ddown-options");if(e.length>0){var t=$(".mc2--dash__nav .mystore").position().left,a=e.width(),i=$(".mc2--dash__nav .nav-content").width();t+a<i?e.css("left",t):e.css("left",i-a)}}),$(".mc2--dash__register .leanne").on("click",function(e){$(this).parent().toggleClass("leanne-open")})}return{_init:function(){e()}}}function J(){function e(){"undefined"==typeof mcbDevices?console.error("Json mcbDevices missing. Cant continue"):(U("https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.0/vue.min.js",t),U("https://maps.googleapis.com/maps/api/js?key=AIzaSyDEu-oeEWxWE343tI2YBBwZihl2UJ5c_Dc",function(){setTimeout(function(){a()},250)})),window.addEventListener("resize",function(){s&&r&&s.fitBounds(r)},!1),window.addEventListener("orientationchange",function(){if(console.log("orient"),s&&r){setTimeout(function(){s.fitBounds(r)},200)}},!1)}function t(){for(var e=0;e<mcbDevices.length;e++)mcbDevices[e].view=!0;new Vue({el:"#mcb2--dash_devices",data:{sortAsc:!1,filterNum:10,prevFilterNum:10,devices:mcbDevices,devicesLen:mcbDevices.length,myActivity:myActivity,filterBy:"status",currentPage:0,search:"",sortBy:["status","model","serial","address"],statusTypes:{service:{0:{tit:"Booked",icn:"icon-svg-howto-cable"},1:{tit:"Scheduling",icn:"icon-svg-howto-sample-paper"},2:{tit:"Allocated",icn:"icon-svg-tick-white"},3:{tit:"Completed",icn:"icon-svg-howto-printer"},4:{tit:"Feedback",icn:"icon-svg-email"}},order:{0:{tit:"Booked",icn:"icon-svg-tick-circle-orange"},1:{tit:"Scheduling",icn:"icon-svg-tick-circle-green"},2:{tit:"Allocated",icn:"icon-svg-tick-white"},3:{tit:"Completed",icn:"icon-svg-update"},4:{tit:"Feedback",icn:"icon-svg-email"}}},infoShow:!0,mapmarkerFilter:"All States",suburbName:"",status:{0:"Ok",1:"Minor",2:"Middle",3:"Major"}},methods:{activityStatus:function(e){return this.statusTypes[e]||null},showExpand:function(e,t){t.view=!t.view},setPage:function(e){this.currentPage=e},randomIndex:function(){return"A"+Math.floor(Math.random()*this.devices.length)},sorted:function(e,t){var a=this.sortAsc?1:-1;return a*e[this.filterBy].localeCompare(t[this.filterBy])},findBy:function(){var e=this.devices,t=String(this.search).toLowerCase();return e.filter(function(e){return!!e&&(!!(e.model&&e.model.toLowerCase().indexOf(t)>=0)||(!!(e.serial&&e.serial.toLowerCase().indexOf(t)>=0)||(!!(e.address&&e.address.toLowerCase().indexOf(t)>=0)||(!!(e.suburb&&e.suburb.toLowerCase().indexOf(t)>=0)||!!(e.statusError&&e.statusError.toLowerCase().indexOf(t)>=0)))))})},toggleInfo:function(e){this.infoShow=e},uniqueKey:function(e){var t=[];return this.devices.forEach(function(a){t.indexOf(a[e])===-1&&t.push(a[e])}),t.push("All States"),t},combined:function(){var e=this.mapmarkerFilter,t=this.suburbName.toLowerCase();r=new google.maps.LatLngBounds;for(var a=0,i=0,o=u.length;i<o;i++)(u[i].state===e||"All States"==e)&&u[i].suburb.toLowerCase().indexOf(t)>=0?(u[i].setVisible(!0),r.extend(u[i].position),a++):u[i].setVisible(!1);a>1?s.fitBounds(r):(s.setCenter(r.getCenter()),s.setZoom(16))}},computed:{isActiveActivity:function(e,t){return!0},filteredItems:function(){var e=""===this.search?this.devices:this.findBy();e=e.sort(this.sorted),this.devicesLen=e.length;var t=this.currentPage*this.filterNum;return"all"===this.filterNum?e.slice(0):e.slice(t,Number(t)+Number(this.filterNum))},totalPages:function(){return Math.ceil(this.devices.length/this.filterNum)},classStyle:function(){return{devStatus:this.status}}},watch:{filterNum:function(){this.currentPage=0},search:function(){""===this.search?this.filterNum=this.prevFilterNum:(this.prevFilterNum=this.filterNum,this.filterNum=1e3)},mapmarkerFilter:function(){this.suburbName="",this.combined()},suburbName:function(){this.combined()}}})}function a(){if(s=new google.maps.Map(document.getElementById("big-map"),{mapTypeId:google.maps.MapTypeId.ROADMAP}),r=new google.maps.LatLngBounds,l=new google.maps.InfoWindow,mcbDevices)for(var e=mcbDevices.length,t=0;t<e;++t)i(t,mcbDevices[t].address)}function i(e,t){var a=d+=100;setTimeout(function(){mcbDevices[e].latlng?n(e):o(e,t)},a)}function o(e,t){if(c[t]){if(""!==c[t])return mcbDevices[e].latlng=c[t],n(e),c[t]}else c[t]="";$.getJSON("https://maps.googleapis.com/maps/api/geocode/json?address="+t+"&sensor=false",null,function(a){a.results[0]&&a.results[0].geometry?(c[t]=a.results[0].geometry.location,mcbDevices[e].latlng=a.results[0].geometry.location,n(e)):console.log(a)})}function n(e){var t=new google.maps.Marker({position:mcbDevices[e].latlng,map:s,state:mcbDevices[e].state,suburb:mcbDevices[e].suburb,animation:google.maps.Animation.DROP,shadow:"none"});r.extend(t.position),google.maps.event.addListener(t,"click",function(e,t){return function(){var a="<div>"+mcbDevices[t].model+"<div><div>"+mcbDevices[t].address+"<div><div>"+mcbDevices[t].suburb+"<div>";l.setContent(a),l.open(s,e)}}(t,e)),e+1===mcbDevices.length&&s.fitBounds(r),u.push(t)}var s,r,l,c={},d=200,u=[];return{_init:function(){e()}}}function Y(){function e(){$(".forms2--elements__input-file").on("change",function(){console.log($(this).prop("files")),$(this).prop("files")&&$(this).prop("files").length>0?($(this).next().text($(this).prop("files")[0].name),$(this).parent().append('<span class="span-hidden">'+$(this).prop("files")[0].name+"</span>"),$(this).siblings(".icon-svg-cross").css("left",$(".span-hidden").width()+25),$(this).siblings(".span-hidden").remove()):console.log("change")}),$(".forms2--elements__input-group .icon-svg-cross").on("click",function(e){console.log("cross");var t=$(this).parent(),a=t.find(".forms2--elements__input-file"),i=t.find(".forms2--elements__input-label"),o=t.find(".icon-svg-cross");a.val(""),i.text(i.attr("data-val")),o.css("left","100%")})}return{_init:function(){e()}}}function H(){function e(){i&&(t(i),a.find('option[data-filter="'+i+'"]').prop("selected",!0)),a.on("change",function(){var e=$(this).find(":selected").attr("data-filter");e&&t(e)})}function t(e){Stackla.WidgetManager.changeFilter("11225",e)}var a=$(".stackla-widget-select"),i=h().sfilter||!1;return{_init:function(){U("//assetscdn.stackla.com/media/js/widget/fluid-embed.js",e)}}}function W(){function e(){$(".howto--videos__journey .help-btn").on("click",function(e){var t=$(this).closest("section");t.find(".share-textarea");t.find(".elq-model").val(I.model),t.find(".elq-url").val(t.attr("data-id")),t.find(".satisfied").val($(this).text().trim()),$.ajax({type:"POST",url:"https://s103126886.t.eloqua.com/e/f2",data:t.find("form").serialize(),success:function(e){t.find(".helpful-content").html("<h4>Thank you for your feedback</h4>")},error:function(e){console.warn("There was an error submitting",e)}})})}function t(){if(j)return j=!1,null;var e=$("#chatbot-content"),t=$('#chatbot-content [id*="chat-"]').last(),a=e.prop("scrollHeight")-t.height();e.stop().animate({scrollTop:a-80},250)}function a(){var e={mg2460:{wifi:"false","lcd-screen":"non-interactive"},mg2560:{wifi:"false","lcd-screen":"non-interactive"},ip110:{wifi:"true","lcd-screen":"non-interactive"},mx726:{wifi:"true","lcd-screen":"interactive","wireless-direct":"false"},mx926:{wifi:"true","lcd-screen":"interactive","wireless-direct":"false"},"pro-1000":{wifi:"true","lcd-screen":"interactive","wireless-direct":"true",ethernet:"true"},"pro-10s":{wifi:"true","lcd-screen":"non-interactive","wireless-direct":"false",ethernet:"true"},"pro-100s":{wifi:"true","lcd-screen":"non-interactive","wireless-direct":"false",ethernet:"true"}};Object.keys(e).forEach(function(t){I.model.toLowerCase().indexOf(t.toLowerCase())>=0&&Object.keys(e[t]).forEach(function(a){I.features[a]=e[t][a]})})}function i(e){if(!e||!e.QueryResult||!e.QueryResult.FulfillmentMessages)return null;for(var t=e.QueryResult.FulfillmentMessages,a=0,i=t.length;a<i;a++)if(t[a].payload&&!t[a].payload.useText)return t[a].payload;return null}function o(){return I?(g(),intents={action:{"explore.glossary":"glossary","support.unbox":"support","support.setup":"support"},glossary:[],support:E},$(".howto--videos__chatbot-full .chatbot-input").on("keypress",function(e){O||(O=!0,s("event",{event:{name:"model_"+I.features["lcd-screen"],parameters:{model:I.model,lcd:I.features["lcd-screen"]}}}));var t=e.keyCode;13==t&&""!=$(this).val()&&(s("text",$(this).val()),c($(this).val()),$(".howto--videos__chatbot-full .chatbot-input").val(""))}),$(".howto--videos__chatbot-full").on("click","button.chat",function(e){var t=$(this),e=jQuery.Event("keypress");e.which=e.keyCode=13;var a=$(".howto--videos__chatbot-full .chatbot-input");t.parent().hasClass("shortcuts")&&(a.val($(this).text()),t.parent().remove()),a.val().length>1&&$(".howto--videos__chatbot-full .chatbot-input").trigger(e)}),void p("I can assist you with your Canon "+I.model)):(console.warn("Terminating chatbot. No local deviceHelp (json)"),null)}function n(){function e(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)}return e()+e()+"-"+e()+"-"+e()+"-"+e()+"-"+e()+e()+e()}function s(e,t){console.log("chat up started");var a=e||"text",i="";i="event"===a?t:{query:t};var o=localStorage.getItem("accessId")?localStorage.getItem("accessId"):null,n=localStorage.getItem("sessId")?localStorage.getItem("sessId"):null;$.ajax({type:"POST",url:_+"query?projectId="+D+"&sessionId="+n+"&accessToken="+o,contentType:"application/json; charset=utf-8",dataType:"json",headers:{Authorization:"Bearer "+o,"CanonId-Secret":"I2UnRAjuL2qE6yk3rEZbaSrB9B1mC9xdRKOnXW3fpqY="},data:JSON.stringify(i),success:function(e){localStorage.setItem("accessId",e.Payload.AccessToken),localStorage.setItem("sessId",e.Payload.SessionId),e.Status&&"OK"===e.Status?r(e.Payload.DialogflowQueryResponse):console.warn("Chatbot - failed to respond.",e.Status)},error:function(){console.warn("Chatbot - failed to respond.")}})}function r(e){console.log(e.QueryResult),console.log("hi");var a=!1,o=i(e);if(B)return B=!1,null;if(!o&&e.QueryResult.AllRequiredParamsPresent&&e.QueryResult.AllRequiredParamsPresent===!0&&e.QueryResult.Parameters&&e.QueryResult.Parameters.redirectTo)for(var n=e.QueryResult.Parameters.redirectTo.split("|"),r=0,c=n.length/3;r<c;r++)if(I.features[n[3*r]]===n[3*r+1]){if(!(n[3*r+2].indexOf("say")>=0)){B=!0,s("text","stop");setTimeout(function(){s("event",{event:{name:n[3*r+2],parameters:{}}})},250);return null}B=!0,s("text","stop")}if(o){var d="";if(o.title&&(d+=o.title),o.useText&&(d+=e.QueryResult.FulfillmentText),o.redirectTo&&o.redirectOnFeature){var u=0,h=0;Object.keys(o.redirectOnFeature).forEach(function(e){e&&o.redirectOnFeature[e]===I.features[e]&&u++,h++}),u===h&&(a=!0,s("event",{event:{name:o.redirectTo,parameters:{}}}))}if(o.body_conditions)for(var r=0,c=o.body_conditions.length;r<c;r++){var u=0,h=0;o.body_conditions[r]&&o.body_conditions[r].params&&Object.keys(o.body_conditions[r].params).forEach(function(t){o.body_conditions[r].params[t]===e.QueryResult.Parameters[t]&&u++,h++}),u===h&&u>0&&(d+=l(o.body_conditions[r].sitecoreid))}if(at&&o.body_nz?d+=o.body_nz:o.body&&(d+=o.body),o.body_sitecoreid&&(d+=l(o.body_sitecoreid)),o.cta&&(d+=o.cta),o.supportCTA&&(d+=o.supportCTA),o.supportUrl&&I[o.supportUrl]&&(d+='<p class="para"><a href="'+I[o.supportUrl]+'" target="_blank" class="external">www.canon.com.au/support</a></p>'),o.glossary)for(var r=0,c=o.glossary.length;r<c;r++)if(o.glossary[r].id===e.QueryResult.Parameters.glossary_terms){at&&o.glossary[r].content_nz?d+=o.glossary[r].content_nz:o.glossary[r].content&&(d+=o.glossary[r].content),o.glossary[r].followUpCTA&&(d+=o.glossary[r].followUpCTA);break}if(o.redirectTo&&o.redirectWhen){var u=0,h=0;Object.keys(o.redirectWhen).forEach(function(t){t&&o.redirectWhen[t]&&e.QueryResult.Parameters&&e.QueryResult.Parameters[t]&&o.redirectWhen[t]===e.QueryResult.Parameters[t]&&u++,h++}),u===h&&(a=!0,s("event",{event:{name:o.redirectTo,parameters:{}}}))}d&&(d=d.split("<p>").join('<p class="para">')),o.followUpCTA&&(d+=o.followUpCTA),a||(p(d.split("printer-model").join(I.model)||"I'm not sure what you mean."),t()),$(".howto--videos__chatbot-full .chatbot-input").val("")}else if(e.QueryResult.FulfillmentMessages&&e.QueryResult.FulfillmentText){var d="";if(e.QueryResult.FulfillmentText.indexOf("payload$$")>0)try{var m=JSON.parse("{"+e.QueryResult.FulfillmentText+"}");m.text&&(d+=m.text),m.followUpCTA&&(d+=m.followUpCTA)}catch(f){d="Oops. I forgot what i was going to say"}else d=e.QueryResult.FulfillmentText;p(d),$(".howto--videos__chatbot-full .chatbot-input").val(""),t()}}function l(e){for(var t=0,a=E.length;t<a;t++)if(E[t].id===e)return E[t].bdy;return""}function c(e){var t='<div class="right conv flexbox"><span class="text">'+e+'</span><span class="icon-svg-user"></span></div>';$(".howto--videos__chatbot-full .content").append(t)}function p(e){var t='<div class="left conv flexbox" id="chat-'+R++ +'"><span class="icon-svg-leanne"></span><div class="body-text">'+e+"</div></div>";$(".howto--videos__chatbot-full .content").append(t)}function f(){h().features&&(I.features["lcd-screen"]=h().features),g(),k=new Vue({el:".howto--videos__journey",data:{mydata:E,printerModel:"MG1234",deviceModel:"iPhone",printerFeatures:I.features,deepLink:N,navHistory:L,docloc:m()},methods:{swapPM:function(e){return e?e.split("printer-model").join(this.printerModel):""},swapPipe:function(e){return e.split("|").join("_")},featureCheck:function(e){if(e.ftr){for(var t=e.ftr.split("|"),a=0,i=0,o=t.length;i<o;i+=2)t&&this.printerFeatures&&this.printerFeatures[t[i]]&&this.printerFeatures[t[i]]===t[i+1]&&(a+=2);return a===t.length}return!0}}}),P||$('.howto--videos__journey a[href^="#"].cta.done').each(function(){$(this).attr("href","").attr("onclick","window.history.go(-1); return false;")}),$('.howto--videos__options a[href^="#"]').on("click",function(e){e.preventDefault(),e.stopPropagation(),w($(this).attr("href"),$(this))}),$('.howto--videos__journey a[href^="#"]').on("click",function(e){var t=$(this).attr("href");return"javascript:history.back();"===t?null:$(this).hasClass("backto-a")&&!P&&"##previous"!==t&&0==$("section"+t).length?(window.history.go(-1),null):(e.preventDefault(),e.stopPropagation(),void w($(this).attr("href"),$(this)))}),$(".howto--videos__journey button.support").on("click",function(e){return b(-1),$(".howto--videos__modal .screen-1").addClass("hide--me"),$(".howto--videos__modal .screen-2").removeClass("hide--me"),null}),$(".howto--videos__journey .callout .ca-heading").on("click",function(e){$(this).next().toggleClass("active")});for(var t=["#unboxstart","#setupstart","#connectstart","#completed"],a=0,i=t.length;a<i;a++)u(t[a])&&v(t[a]);P?$(".howto--videos__options-solution, .howto--videos__options").removeClass("hide--me").addClass("fadeIn"):(T=!0,$(".howto--videos__options").remove(),N?(w("#"+N,$(this)),$(".howto--videos__journey .done.cta").addClass("hide--me"),$(".howto--videos__journey .backto-a").addClass("vis--me")):w("#connect",$(this))),$(".howto--videos__modal .buttons .btn").on("click",function(){"yes"===$(this).attr("data-type")?(b(),$(".progress-point.complete").addClass("done"),d("#completed",!0,180)):($(".howto--videos__modal .screen-1").addClass("hide--me"),$(".howto--videos__modal .screen-2").removeClass("hide--me"))}),$(".howto--videos__modal .close").on("click",function(e){b()}),$(".howto--videos__journey .share-btn").on("click",function(e){var t=$(this).closest("section"),a=t.find(".share-textarea");if(a.focus(),navigator.userAgent.match(/ipad|ipod|iphone/i)){var i=a.get(0),o=i.contentEditable,n=i.readOnly;i.contentEditable=!0,i.readOnly=!0;var s=document.createRange();s.selectNodeContents(i);var r=window.getSelection();r.removeAllRanges(),r.addRange(s),i.setSelectionRange(0,999999),i.contentEditable=o,i.readOnly=n}else a.select();try{var l=document.execCommand("copy");if(l){t.find(".share-msg").addClass("is-active");setTimeout(function(){t.find(".share-msg").removeClass("is-active")},6e3)}}catch(c){console.log("Copy to clipboard failed")}a.blur()}),e()}function g(){var e=[];e=I.content,Object.keys(e).forEach(function(t){for(var a=0,i=E.length;a<i;a++)if(E[a].id===t&&e[t]&&e[t].length>0){E[a].bdy=e[t];break}})}function b(e){e===-1?(A=!0,$(".howto--videos__modal").removeClass("hide--me"),$("html,body").addClass("f-open"),$(document).on("keyup",function(e){27==e.keyCode&&A&&b()})):(A=!1,TweenMax.fromTo($(".howto--videos__modal .outer"),.3,{css:{opacity:1}},{css:{opacity:0},onComplete:function(){$(".howto--videos__modal").addClass("hide--me"),$("html,body").removeClass("f-open"),$(document).off("keyup"),$(".howto--videos__modal .outer").css("opacity","1")}}))}function y(e){for(var t=e.split("#")[1],a=0,i=E.length;a<i;a++)if(E[a].id===t){L.push(E[a].nvi),E[a].nv=L.slice();break}}function v(e){switch(e){case"#unboxstart":$(".progress-point.unbox").addClass("done");break;case"#setupstart":$(".progress-point.setup").addClass("done");break;case"#connectstart":$(".progress-point.connect").addClass("done");break;case"#completed":$(".progress-point.complete").addClass("done")}}function w(e,t){var a=t;"##previous"===e&&(e=C.slice(-2)[0]);var i=$(e),o=!0;return i.addClass("active"),void 0===i.offset().top&&window.history.go(-1),i.offset().top>$(document).scrollTop()?(C.push(e),y(e),"#setup"===e&&$(".progress-point.unbox").addClass("done"),"#connect"===e&&$(".progress-point.unbox,.progress-point.setup").addClass("done")):(o=!1,v(e),L=L.slice(0,-2),y(e)),T?(T=!1,null):void $("html,body").stop().animate({scrollTop:i.offset().top-x},550).promise().done(function(){o||($(C.slice(-1)[0]).removeClass("active"),C=C.slice(0,-1)),!o&&a.attr("data-done")&&(C=[],$(".howto--videos__journey section.active").removeClass("active"),e.indexOf("connect")>=0&&(b(-1),$(".howto--videos__modal .screen-2").addClass("hide--me"),$(".howto--videos__modal .screen-1").removeClass("hide--me"))),o||"#connectstart"!==e||(d("#unboxstart",!0,180),d("#setupstart",!0,180)),o||d(e,!0,180),M&&(M=!1,x=70)})}function S(){$(".howto--videos__summary .frms2--elements__info").on("click",function(){$(this).parent().toggleClass("active")})}var k,E=[{id:"unbox",ttl:"Let's check everything's in the box",nv:[],nvi:"Unbox",nav:{1:"Whats in the box"},don:"unboxstart",sup:!0,hlp:!0},{id:"setup",ttl:"Setting up your printer",nv:[],nvi:"Printer setup",nav:{1:"Setup"},don:"setupstart",sup:!0},{id:"connect",ttl:"Lets connect your printer to your device(s)",nv:[],nvi:"Connection type",atc:[{tit:"With WiFi",url:"connect_csm",ftr:"lcd-screen|non-interactive|wifi|true|wireless-direct|true"},{tit:"With WiFi",url:"connect_type",ftr:"lcd-screen|interactive|wifi|true|wireless-direct|true"},{tit:"With WiFi",url:"connect_ew_int",ftr:"lcd-screen|interactive|wireless-direct|false"},{tit:"With WiFi",url:"connect_csm",ftr:"lcd-screen|non-interactive|ethernet|true"},{tit:"With USB",url:"connect_usb"},{tit:"With Ethernet",url:"connect_eth",ftr:"ethernet|true"}],cai:[{head:"What's Wi-Fi?",info:"Wi-Fi is how many devices are able to speak with each other without cables. This covers devices such as computers, smartphones and tablets, and even printers.  This means you can share your printer, without extra cables, among multiple devices and people in your home."}],bdy:"<p>Your new Canon printer is Wi-Fi enabled, which means you can connect it wirelessly to your computers, smartphones and tablets.</p><p>You can also connect it to a computer with a USB cable if you’d prefer.</p><p>Don't worry, no matter what you choose, we will take you through it step-by-step to get you printing in no time.</p><p>So, how would you like to connect?</p>"},{id:"connect_usb",ttl:"Get your USB cable ready",nv:[],nvi:"USB",bck:"connect",don:"connectstart",hlp:!0,atd:[{tit:"I'd prefer Wi-Fi",url:"connect_csm",
ftr:"lcd-screen|non-interactive|wifi|true|ethernet|false|wireless-direct|true"},{tit:"I'd prefer Wi-Fi",url:"connect_type",ftr:"lcd-screen|interactive|wifi|true|wireless-direct|true"}],sup:!0,cai:[{head:"I don't have a USB cable.",ftr:"lcd-screen|non-interactive",info:"To connect your printer to your computer, you'll need a 'USB A to B' printer cable, available from the shop where you purchased the printer. If you've had a printer before, you've probably got one at home already."},{head:"Which driver should I download?.",ftr:"lcd-screen|non-interactive",info:'Make sure you click the link above on the device you are setting up (unless you are using the disc that came with your printer). Our website should automatically detect which operating system you are using and only show you those results. Look for the "Full Driver & Software Package" - if you use the search, make sure to pick the correct operating system (Windows or Mac)'},{head:"I don't have a USB cable for my PIXMA or MAXIFY printer?",ftr:"lcd-screen|interactive",info:"In order to connect your printer to your computer, you'll need a 'USB A to B' printer cable, available from the shop where you purchased the printer. If you've had a printer before, you've probably got one at home already. We suggest you check the random kitchen drawer that contains the stuff that you don't know what else to do with."},{head:"I don't have a USB cable for my SELPHY printer?",ftr:"lcd-screen|interactive",info:"In order to connect your printer to your computer, you'll need a 'USB A to Mini B' cable, available from the shop where you purchased the printer. If you have had a Canon Digital Camera before, you've probably got one at home already."},{head:"Which driver should I download?",ftr:"lcd-screen|interactive",info:'Make sure you click the link above on the device you are setting up (unless you are using the disc that came with your printer). Our website should automatically detect which operating system you are using and only show you those results. Look for the "Full Driver & Software Package" - if you use the search, make sure to pick the correct operating system (Windows or Mac).'}]},{id:"connect_eth",ttl:"Connecting via ethernet",nv:[],nvi:"Ethernet",bck:"connect",bdy:'<p class="para">In order to connect your printer to your computer network, you\'ll need an Ethernet cable (sold separately).<p/>Prepare your printer for connecting to your wired network:<ul class="list-items"><li class="item"><span class="icon-svg-howto-generic"></span>Ensure the printer is turned on.</li><li class="item"><span class="icon-svg-howto-generic"></span>Remove the cap from the upper port located on the right side at the back of the printer</li><li class="item"><span class="icon-svg-howto-generic"></span>Connect the printer and a network device (router, etc) with an ethernet cable. Ensure you use the upper port (Ethernet) rather than the lower port (USB)</li><li class="item"><span class="icon-svg-howto-generic"></span>When using a router, connect the printer and computer to the LAN side (same network segment)</li><li class="item"><span class="icon-svg-howto-generic"></span>Hold down the RESUME/CANCEL button on the printer until the POWER lamp flashes 11 times, then release the RESUME/CANCEL button after the eleventh flash</li><li class="item"><span class="icon-svg-howto-generic"></span>The network connection setup is now complete</li></ul>',cta:{connect_ew_non:"Continue"}},{id:"connect_csm",ttl:"Double check your printer's in Cableless Setup Mode",nv:[],nvi:"Cableless Setup",nav:{1:"Connect",2:"Mode"},bck:"connect",atc:[{tit:"Yes",url:"connect_type",ftr:"ethernet|false"},{tit:"Yes",url:"connect_ew_non",ftr:"ethernet|true"},{tit:"No",url:"connect_csm_no"},{tit:"I'm not sure",url:"connect_csm_no"}],cai:[{head:"What is Cableless Setup Mode?",info:"In the Canon printer range, most entry level models don't come with a screen or alpha numerical keypad to manually browse and join Wi-Fi networks.  This makes it a little less intuitive to set up your printer with Wi-Fi.  But we're right here to help you through the process.  In a nutshell, Cableless Setup Mode is a temporary unsecured Wi-Fi network that is only active when you are setting up the machine.  The way it works is that you connect to that Wi-Fi network with your device, and then step through a configuration process to apply your preferred Wi-Fi configuration setting."}]},{id:"connect_csm_no",ttl:"Prepare your printer for Cableless Setup Mode",nv:[],nvi:"Activating CSM",nav:{1:"Connect",2:"Mode",3:"Setup"},atc:[{tit:"Continue",url:"connect_type",ftr:"ethernet|false"},{tit:"Continue",url:"connect_ew_non",ftr:"ethernet|true"}],bck:"connect_csm",sup:!0},{id:"connect_type",ttl:"Do you already have a wireless network?",nv:[],nvi:"Wi-Fi Method",nav:{1:"Connect",2:"Wifi"},bck:"#previous",atc:[{tit:"Add to your existing network",url:"connect_ew_non",ftr:"lcd-screen|non-interactive"},{tit:"Add to your existing network",url:"connect_ew_int",ftr:"lcd-screen|interactive"},{tit:"Wireless direct",url:"connect_wd_non",ftr:"lcd-screen|non-interactive"},{tit:"Wireless direct",url:"connect_wd_int",ftr:"lcd-screen|interactive"}],sup:!0},{id:"connect_wd_non",ttl:"Connecting directly to your printer's Wi-Fi",nv:[],nvi:"Wireless direct",nav:{1:"Connect",2:"Wifi",3:"Direct"},bck:"connect_type",cta:{connect_wd_non_android:"Android mobile or tablet",connect_wd_non_ios:"Apple iOS mobile device",connect_wd_non_pc:"PC or Mac Computer"},cai:[{head:"I have more than one device I want to connect.",info:"You can connect multiple devices to your Canon printer. However, you will need to use one device to make that initial connection, so it can then apply the correct settings to the printer. Once this is done, more devices can be easily connected."}]},{id:"connect_wd_int",ttl:"Enabling wireless direct - part 1",nv:[],nvi:"Direct",nav:{1:"Connect",2:"Wifi",3:"Part I"},bck:"connect_type",cta:{connect_wd_int_p2:"Continue"}},{id:"connect_wd_int_p2",ttl:"Enabling wireless direct - part 2",nv:[],nvi:"Direct 2",nav:{1:"Connect",2:"Wifi",3:"Part I",4:"Part II"},bck:"connect_wd_int",don:"connectstart",cta:{connect_apps:"Continue"}},{id:"connect_ew_int",ttl:"Existing network instruction",nv:[],nvi:"Existing",nav:{1:"Connect",2:"Wifi",3:"Network"},bck:"#previous",don:"connectstart",cta:{connect_apps:"Continue"}},{id:"connect_wd_non_pc",ttl:"Computer setup",nv:[],nvi:"PC",nav:{1:"Connect",2:"Wifi",3:"Direct",4:"PC"},don:"connectstart",hlp:!0,cta:{connect_wd_non_add:"Connect more devices?"},bck:"connect_wd_non",sup:!0,don:"connectstart"},{id:"connect_wd_non_android",ttl:"Connecting an Android",nv:[],nvi:"Android",nav:{1:"Connect",2:"Wifi",3:"Direct",4:"Android"},don:"connectstart",hlp:!0,cta:{connect_wd_non_add:"Connecting additional devices"},bck:"connect_wd_non",sup:!0,don:"connectstart"},{id:"connect_wd_non_ios",ttl:"iOS device setup",nv:[],nvi:"iOS",nav:{1:"Connect",2:"Wifi",3:"Direct",4:"iOS"},don:"connectstart",hlp:!0,cta:{connect_wd_non_add:"Connect more devices?"},bck:"connect_wd_non",don:"connectstart"},{id:"connect_wd_non_add",ttl:"Connecting additional devices",nv:[],nvi:"More devices",nav:{1:"Connect",2:"Wifi",3:"Direct",4:"More"},cta:{connect_apps:"Continue"},bck:"#previous",sup:!0},{id:"connect_ew_non",ttl:"Connecting to your existing Wi-Fi network",nv:[],nvi:"Existing Wi-Fi",nav:{1:"Connect",2:"Wifi",3:"Network"},bck:"#previous",cta:{connect_ew_non_android:"Android mobile or tablet",connect_ew_non_ios:"Apple iOS mobile or tablet",connect_ew_non_pc:"PC or Mac Computer"},cai:[{head:"Why do I need to choose one particular device? I have lot's that I want to connect.",info:"You can connect multiple devices to your Canon printer. However, you will need to use one device to make that initial connection, so it can then apply the correct settings to the printer. Once this is done, more devices can be connected with ease."}]},{id:"connect_ew_non_pc",ttl:"Computer setup",nv:[],nvi:"PC",nav:{1:"Connect",2:"Wifi",3:"Network",4:"PC"},cta:{connect_apps:"Connect more devices?"},bck:"connect_ew_non",sup:!0,don:"connectstart"},{id:"connect_ew_non_android",ttl:"Android device setup",nv:[],nvi:"Android",nav:{1:"Connect",2:"Wifi",3:"Network",4:"Android"},cta:{connect_apps:"Connect more devices?"},bck:"connect_ew_non",sup:!0,don:"connectstart"},{id:"connect_ew_non_ios",ttl:"iOS device setup",nv:[],nvi:"iOS",nav:{1:"Connect",2:"Wifi",3:"Network",4:"iOS"},cta:{connect_apps:"Connect more devices?"},bck:"connect_ew_non",sup:!0,don:"connectstart"},{id:"connect_apps",ttl:"Just one last step",nv:[],nvi:"Apps and software",nav:{1:"Connect",2:"Apps"},bck:"#previous",cta:{connect_apps_pc:"Desktop Computer",connect_apps_device:"Mobile or Tablet"}},{id:"connect_apps_pc",ttl:"Installing apps and software for your computer",nv:[],nvi:"PC",nav:{1:"Connect",2:"Apps",3:"Computer"},bck:"connect_apps",sup:!0,cai:[{head:"Which driver should I download?",info:'Make sure you click the link above on the device you are setting up (unless you are using the disc that came with your printer). Our website should automatically detect which operating system you are using and only show you those results. Look for the "Full Driver & Software Package" - if you use the search, make sure to pick the correct operating system (Windows or Mac).'}],ext:"exit"},{id:"connect_apps_device",ttl:"Installing apps and software for your smart device",nv:[],nvi:"Smart device",nav:{1:"Connect",2:"Apps",3:"Device"},bck:"connect_apps",sup:!0,ext:"exit"}],C=[],I=window.myDeviceHelp||"",P=h().firsttime||!1,N=h().journey||!1,T=(h().model||!1,!1),M=!0,x=140,L=[],A=!1,_="https://uatapi.canon.com.au/hub/v2/gcp/dialogflow/",D="printassistchatbot-wjqeel",R=1,j=(n(),!0),O=!1,B=!1;try{I.features["lcd-screen"]=h().lcd||I.features["lcd-screen"],I.model=h().model||I.model}catch(G){console.warn("Chatbot features missing json")}return I&&I.features&&(I.features.wifi="true",I.features["wireless-direct"]="true",I.features.ethernet="false"),a(),{_init:function(){var e=location.href.indexOf("canon")>0?"https://unpkg.com/vue@2.4.2/dist/vue.min.js":"js/vendor/vuejs/vue.min.js";U(e,f)},_chatbotinit:function(){o()},_summaryinit:function(){S()}}}function z(){function e(){function e(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)}return e()+e()+"-"+e()+"-"+e()+"-"+e()+"-"+e()+e()+e()}function t(){return l&&l.content?(a(),n=new Vue({el:".howto--videos__journey.camera-assist",data:{mydata:s,printerModel:"MG1234",deviceModel:"iPhone",cameraFeatures:l.features,cameraContent:l.content,deepLink:c,navHistory:f,docloc:m()},methods:{button:function(e,t,a){if(!e.tit||!e.url)return null;var i="View drivers & downloads"===e.tit?'<a href="'+b+'" class="btn--2 cta">'+e.tit+"</a>":'<a href="'+e.url+'" class="btn--2 cta">'+e.tit+"</a>";return e.cnt&&(!this.cameraContent[e.cnt]||this.cameraContent[e.cnt]&&this.cameraContent[e.cnt].length<=8)&&(i=null),e.his&&(0===e.his.indexOf("!")&&r.indexOf(e.his.substr(1,20))>-1?i=null:0!==e.his.indexOf("!")&&r.indexOf(e.his)<=0&&(i=null)),i}}}),$('.howto--videos__journey a[href^="#"]').on("click",function(e){e.preventDefault(),e.stopPropagation(),o($(this).attr("href"),$(this))}),d=!0,void(c?(o("#"+c,$(this)),$(".howto--videos__journey .done.cta").addClass("hide--me"),$(".howto--videos__journey .backto-a").addClass("vis--me")):o("#start",$(this)))):(console.warn("Camera assist: var myDeviceHelp missing from page. Terminating"),null)}function a(){l.features.hasContent={};var e=[];e=l.content,Object.keys(e).forEach(function(t){for(var a=0,i=s.length;a<i;a++)if(s[a].id===t&&e[t]&&e[t].length>0){s[a].bdy=e[t];break}})}function i(e){for(var t=e.split("#")[1],a=0,i=s.length;a<i;a++)if(s[a].id===t){f.push(s[a].nvi),s[a].nv=f.slice();break}}function o(e,t){var a=t,o=!1;"##previous"===e&&(o=!0,e=r.slice(-2)[0]);var n=$(e),s=!0;if(n.addClass("active"),!n||!n.offset()||!n.offset().top)return console.warn("Camera assist. Cant find",n,". Terminating."),null;if(void 0===n.offset().top&&window.history.go(-1),n.offset().top>$(document).scrollTop()&&!o){r.push(e),i(e);g++;n.css("order",g++)}else o?(s=!1,f=f.slice(0,-2),i(e)):(r.push(e),i(e),n.css("order",g++));return d?(d=!1,null):void $("html,body").stop().animate({scrollTop:n.offset().top-p},550).promise().done(function(){s||($(r.slice(-1)[0]).removeClass("active"),r=r.slice(0,-1)),!s&&a.attr("data-done")&&(r=[],$(".howto--videos__journey section.active").removeClass("active")),u&&(u=!1,p=70)})}var n,s=[{id:"start",ttl:"Features and connectivity",nv:[],nvi:"Start",btn:[{tit:"Get to know your camera",url:"#skill",cnt:"skill"},{tit:"Connect to my smartphone",url:"#connect_wifi",cnt:"connect_wifi"}]},{id:"connect_wifi",ttl:"Connecting a smartphone",nv:[],nvi:"Wireless",bck:"#previous",btn:[{tit:"Apple",url:"#connect_wifi_ios",cnt:"connect_wifi_ios"},{tit:"Android",url:"#connect_wifi_android",cnt:"connect_wifi_android"}]},{id:"connect_wifi_ios",ttl:"Connecting an Apple device",nv:[],nvi:"Apple",bck:"#previous",btn:[{tit:"Get to know your camera",url:"#skill",cnt:"skill"},{tit:"View drivers & downloads",url:"/cameras/eos-rp/support?option=drivers"},{tit:"View more learning articles",url:"/explore/learning"}]},{id:"connect_wifi_android",ttl:"Connecting an Android",nv:[],nvi:"Android",bck:"#previous",btn:[{tit:"Get to know your camera",url:"#skill",cnt:"skill"},{tit:"View drivers & downloads",url:"/cameras/eos-rp/support?option=drivers"},{tit:"View more learning articles",url:"/explore/learning"}]},{id:"skill",ttl:"What would you like to do?",nv:[],nvi:"Features",bck:"#previous",btn:[{tit:"Take a tour of the camera",url:"#skill_101",cnt:"skill_101"},{tit:"View advanced tips and techniques",url:"#skill_201",cnt:"skill_201"}]},{id:"skill_101",ttl:"Product tour",nv:[],nvi:"Product tour",bck:"#previous",btn:[{tit:"View advanced tips and techniques",url:"#skill_201",cnt:"skill_201"},{tit:"View drivers & downloads",url:"/cameras/eos-rp/support?option=drivers"},{tit:"Connect to my smartphone",url:"#connect_wifi",his:"!#connect_wifi",cnt:"connect_wifi"}]},{id:"skill_201",ttl:"Advanced tips and techniques",nv:[],nvi:"Advanced features",bck:"#previous",btn:[{tit:"View drivers & downloads",url:"/cameras/eos-rp/support?option=drivers"},{tit:"View more photography tips",url:"/get-inspired/photography-tips"},{tit:"Connect to my smartphone",url:"#connect_wifi",his:"!#connect_wifi",cnt:"connect_wifi"}]}],r=[],l=window.myDeviceHelp||"",c=h().journey||!1,d=(h().model||!1,!1),u=!0,p=140,f=[],g=(e(),1),b=l.productUrl+"/support?option=drivers";return{_init:function(){var e=location.href.indexOf("canon")>0?"https://unpkg.com/vue@2.4.2/dist/vue.min.js":"js/vendor/vuejs/vue.min.js";U(e,t)}}}function X(){function e(){t.find(".click-more button").on("click",function(){$that=$(this),$that.closest(".item").find(".feature").toggleClass("open")})}var t=$(".online--prop__product");return{_init:function(){e()}}}function q(){Ue=!0;setTimeout(function(){Ue=!1},15)}function V(){var e=700/480,t=$('[class*="tiled--"] [class*="tile--"] div.aratio--35-24 img');t.each(function(){if($that=$(this),$that.attr("width")&&$that.attr("height")){var t=$that.attr("width")/$that.attr("height");$that.attr("data-src")||$that.attr("src");$that.attr("src").indexOf("mw")<0,$that.attr("data-width")&&$that.attr("data-height")&&(t-e!==0&&t<e&&$that.addClass("imgfix--width"),$that.attr("height")>$that.attr("data-height"),$that.attr("width")>$that.attr("data-width"))}})}function K(){function e(){Q(t,"is-active"),Q($(".canonedge--header h2.heading"),"is-active","ul.sidenav-list"),t.on("click",function(){console.log("click"),a.toggleClass("is-active")}),$(".canonedge--header .sidenav-list").each(function(){var e=$(this),t=50;e.find(".sidenav-item").each(function(){$(this).css("transition-delay",(t+=10)+"ms"),$(this).find(".link").css("transition-delay",(t+=5)+"ms")})})}var t=$(".canonedge--header .hamburger"),a=$(".canonedge--header .side-nav");return{_init:function(){e()}}}function Q(e,t,a){e.on("click",function(){$(this).toggleClass(t),$(this).next(a).toggleClass(t)})}function Z(){function e(e){const t=e.closest(".prod__relacc");return{parent:t,obj:e,availWidth:t.find(".col-gc").outerWidth(),numItems:t.find(".items .item").length,gallery:t.find(".items")}}function t(){$(".prod__relacc .gallery").each(function(){var t=e($(this).find(".col-gc"));t.availWidth<170*t.numItems?$(this).find(".col-gl,.col-gr").css("visibility","initial"):$(this).find(".col-gl,.col-gr").css("visibility","hidden")})}$(".prod__relacc .col-gr").on("click",function(){const t=e($(this)),a=t.gallery.css("transform").replace(/[^0-9\-.,]/g,"").split(","),i=a[12]||a[4],o=Number(i)-170,n=(170*Number(t.numItems)+Number(o))/170;n>=Math.floor(t.availWidth/170)&&t.gallery.css({transform:"translateX("+o+"px)"})}),$(".prod__relacc .col-gl").on("click",function(){const t=e($(this)),a=t.gallery.css("transform").replace(/[^0-9\-.,]/g,"").split(","),i=a[12]||a[4];var o=Number(i)+170;o>0&&(o=0),t.gallery.css({transform:"translateX("+o+"px)"})}),$(".prod__relacc .items").on("click","li",function(t){const a=e($(this)),i=a.gallery.css("transform").replace(/[^0-9\-.,]/g,"").split(","),o=Number(i[12]||i[4]),n=Number($(this).index()+1),s=o+170*n-a.availWidth;if(s>0&&a.gallery.css({transform:"translateX("+(o-s)+"px)"}),s<-170){var r=o+(170*n+o);r>0&&(r=0),a.gallery.css({transform:"translateX("+r+"px)"})}a.parent.find(".details img"),a.parent.find(".details img").attr("src",$(this).find("img").attr("src")),a.parent.find(".details p").html($(this).attr("data-copy")),a.parent.find(".details h2").html($(this).attr("data-title")),a.parent.find(".details a.link").attr("href",$(this).attr("data-url"))}),window.addEventListener("resize",t,!1),window.addEventListener("orientationchange",t,!1),t()}function ee(){function e(){if(c&&c.indexOf("/")>0){const e=(c.split("/")[0],c.split("/")[1]);$(".prod__360hot #wr360PlayerDesktop").css("height",e+"px"),$(".prod__360hot #wr360PlayerMobile").css("height",e+"px")}a("#wr360PlayerDesktop",s,"desktop.xml"),a("#wr360PlayerMobile",r,"mobile.xml"),window.addEventListener("resize",t,!1),window.addEventListener("orientationchange",t,!1),t()}function t(){if(window.innerWidth<=768){var e=$(".prod__360hot .left").outerHeight(),t=Math.max($(".prod__360hot .right").outerHeight(),336*$(".prod__360hot .right").outerWidth()/600,$(".prod__360hot .wr360_player-outer").outerHeight());e+t>10?i(e+t+64):setTimeout(function(){var e=$(".prod__360hot .left").innerHeight(),t=$(".prod__360hot .right").innerHeight();i(e+t>100?e+t+32:600)},750)}}function a(e,t,a){$(e).rotator({licenseFileURL:l+"license.txt",configFileURL:t+a,graphicsPath:t+"images/",zIndexLayersOn:!1,responsiveBaseWidth:600,responsiveMinHeight:0,googleEventTracking:!1})}function i(e){const t=Math.min(e,600);$(".prod__360hot .bck-img").css({height:t+"px"})}function o(e,t){var a=document.createElement("script");a.setAttribute("src",e),a.onload=t,document.body.appendChild(a)}console.log("360 loaded");const n=$(".prod__360hot"),s=n.attr("data-desktop"),r=n.attr("data-mobile"),l=n.attr("data-imagerotator"),c=n.attr("data-ratio")||"600/335";s.length&&l.length&&o(l+"imagerotator.js",e)}function te(){function e(e,t){var a=document.createElement("script");a.setAttribute("src",e),a.onload=t,document.body.appendChild(a)}function t(){P(),ge("product-control"),ye(),$(".img__gallery .gallery .items").on("click","li",function(){$(".img__gallery .litebox").removeClass("hide--me"),S(event)}),$("#filter-destination").on("change",function(){y()}),$("#litebox-close").on("click",function(){console.log("close clicked"),$(".img__gallery .litebox").addClass("hide--me")}),$("#eligible-products-close").on("click",function(){console.log("close clicked"),$(".camp__xmas18-prod .litebox").addClass("hide--me")}),$("#eligible-products-open").on("click",function(){$(".camp__xmas18-prod .litebox").removeClass("hide--me")}),$("#eligible-products-open-mobile").on("click",function(){$(".camp__xmas18-prod .litebox").removeClass("hide--me")}),$("#product-select").on("change",function(){N()})}console.log("image gallery"),e("https://cdnjs.cloudflare.com/ajax/libs/typeahead.js/0.11.1/typeahead.bundle.min.js",t)}function ae(){$(".prod__specs").each(function(){$(this).find("li a").on("click",function(e){var t=$(this).closest(".item").toggleClass("active");$(this).closest(".items").find(".item.active").not(t).removeClass("active");e.preventDefault()})})}function ie(){$(".navigation__category-page .mobile-only").on("click",function(){$(this).parent().toggleClass("mobile")})}function oe(){var e=window.matchMedia("only screen and (max-width: 768px)");$(".link__cta .hover-content").each(function(t,a){e.matches?$(this).css("top","50%"):$(this).css("top","-"+.5*$(this).height()+"px")}),$('.link__cta [data-type*="cta-"]').on("mouseover touchstart",function(e){$(this).find(".hover-content").css("display","block")}),$('.link__cta [data-type*="cta-"]').on("mouseleave",function(e){$(this).find(".hover-content").css("display","none")}),$('.link__cta [data-type*="cta-"] .hover-content').on("touchstart",function(e){e.stopPropagation(),$(this).css("display","none")})}function ne(){function e(){$(".ecrm__trigger-form").toggleClass("open"),i=!i,console.log("trigger ecrm")}var t=$(window).width(),a=$(window).height(),i=!1;if(Math.max(t,a)>1024){setTimeout(function(){i||e()},3e4)}$(".ecrm__trigger-form .heading, .ecrm__trigger-form .close").on("click",function(){e()})}function se(){var e=Number($("#canada-count").text()),t=Number($("#egypt-count").text()),a=Number($("#iceland-count").text()),i=Number($("#india-count").text()),o=Number($("#japan-count").text()),n=Number($("#lapland-count").text()),s=Number($("#madagascar-count").text()),r=Number($("#morocco-count").text()),l=Number($("#peru-count").text()),c=Number($("#baltic-count").text()),d=e+t+a+i+o+n+s+r+l+c;return console.log("total selected count",d),Number(d)}function re(e){var t=se(),a=Number($("#totalNumberOfEntries").text());return console.log("total entries",a),console.log("total selected entries",t),console.log("entryValue",e),e<a&&a>t?(e++,$(".xmas-form-container .error-msg").css("display","none")):$(".xmas-form-container .error-msg").css("display","block"),e}function le(e){return $(".xmas-form-container .error-msg").css("display","none"),e>0&&e--,e}function ce(){var e=$("#canada-count").text(),t=$("#egypt-count").text(),a=$("#iceland-count").text(),i=$("#india-count").text(),o=$("#japan-count").text(),n=$("#lapland-count").text(),s=$("#madagascar-count").text(),r=$("#morocco-count").text(),l=$("#peru-count").text(),c=$("#baltic-count").text(),d=[];return Number(e)>0&&d.push({Name:"Canada",Entries:e}),Number(t)>0&&d.push({Name:"Egypt",Entries:t}),Number(a)>0&&d.push({Name:"Iceland",Entries:a}),Number(i)>0&&d.push({Name:"India",Entries:i}),Number(o)>0&&d.push({Name:"Japan",Entries:o}),Number(n)>0&&d.push({Name:"Lapland",Entries:n}),Number(s)>0&&d.push({Name:"Madagascar",Entries:s}),Number(r)>0&&d.push({Name:"Morocco",Entries:r}),Number(l)>0&&d.push({Name:"Peru",Entries:l}),Number(c)>0&&d.push({Name:"Baltic",Entries:c}),console.log(d),d}function de(){for(var e=[],t=0;t<50;t++){var a;if(a=0===t?$("#product-control"):t<10?$("#product-control_0"+t):$("#product-control_"+t),1===a.length){var i=a.find("#productTypeahead1").val(),o=a.find("#productSerialNumber1").val(),n=a.find(".save-button").text();i&&i.length>0&&o&&o.length>0&&n&&n.indexOf("Saved")>-1&&e.push({Name:i,SerialNumber:o,SitecoreId:i})}}return console.log("productsObject",e),e}function ue(){var e=de(),t=0;$.each(e,function(e,a){$.each(tt,function(e,i){i.product===a.Name&&(console.log(e,a.Name),t=Number(t)+Number(i.entries),console.log(t))})}),$("#totalNumberOfEntries").text(t.toString())}function pe(e){console.log("removing productControl",e),ue()}function he(e){var t=e.files[0],a=new FileReader;a.readAsDataURL(t),a.onload=function(){mt=a.result.split(",")[0],ht=a.result.split(",")[1];var e=mt.indexOf(";");mt=mt.substring(5,e)},a.onerror=function(e){ht="",mt=""}}function me(e){$("html, body").animate({scrollTop:$(e).offset().top-100},250),$(e).focus()}function fe(){var e=$("#firstName").val(),t=$("#lastName").val(),a=$("#primaryContactNumber").val(),i=$("#email").val(),o=$("#postcode").val(),n=$("#purchaseDate").val(),s=$("#retailerName").val()?$("#retailerName").val().toUpperCase():"",r=$("#retailerState").val()?$("#retailerState").val().toUpperCase():"",l=$("#retailerOther").val(),c=(document.getElementById("terms").checked,document.getElementById("signUp").checked),d=de(),u=ce(),p=Number($("#totalNumberOfEntries").text()),h=$(".camp__xmas18-form").attr("data-api"),m=[],f="Upload",g=$("input[type=radio][name=ReceiptOption]:checked").val(),b="OTHER*"==s;if(g.indexOf("Upload")>=0||(f="Post"),console.log("Validate user details"),!Te(d))return me("#productTypeahead1"),null;if(p<1)return me("#holidays-start"),null;if(u.length<1)return me("#holidays-start"),null;if(!Ce(n))return me("#purchaseDate"),null;if(!Ie(s))return me("#retailerName"),null;if(!Ne(l,s))return me("#retailerOther"),$("#retailerOtherErrorMessage").css("display","block"),null;if($("#retailerOtherErrorMessage").css("display","none"),!Pe(r))return me("#retailerState"),null;if("Upload"===f&&(!ft||""==ft||0==ft.length))return me("#proof-of-purchase"),null;if(!Se(e))return me("#firstName"),null;if(!Se(t))return me("#lastName"),null;if(!ke(a))return me("#primaryContactNumber"),null;if(!$e(i))return me("#email"),null;if(!Ee(o))return me("#postcode"),null;ht&&m.push({FileName:ft,ContentType:mt,Content:ht});var y={Data:{FirstName:e,LastName:t,ContactNumber:a,EmailAddress:i,PostCode:o,DatePurchased:n,RetailerName:b?l:s,RetailerLocation:r,PurchasedOnline:!0,ClaimMethod:f,CashbackAmount:p,PaymentOption:"Holiday",Products:d,Entries:u,SubscribedToEloquaForm:c},Files:m};console.log("json string: ",JSON.stringify(y)),console.log("cashback amount",p),console.log("xmasFormData object",y),h&&$.ajax({type:"POST",url:h,dataType:"json",contentType:"application/json",async:!1,data:JSON.stringify(y),error:function(){console.log("ajax fail")},success:function(){console.log("success"),$("#product-form-section").hide(),$("#thankyou-page").show(),me("#thankyou-page")}})}function ge(e){var t=[],a="#"+e;tt&&($.each(tt,function(e,a){t.push(a.product)}),$(a+" .product-typeahead .typeahead").typeahead({hint:!0,highlight:!0,minLength:1},{name:"products",source:gt(t)}),$(a+" .product-typeahead .typeahead").typeahead("val",""),$(a+" .serial-number").val(""))}function be(e){var e="#"+e,t=$(e+" .save-button"),a=($(e+" .typeahead"),$(e+" .serial-number"),$(e+" #productTypeahead1").val()),i=$(e+" #productSerialNumber1").val();a&&i&&(t.html("Saved &#10003;"),ue())}function ye(){}function ve(){var e=document.getElementById("terms");e.checked?$("#submit-entry").prop("disabled",!1):$("#submit-entry").prop("disabled",!0)}function we(e){var t=e.clone(),a=bt+1;bt=a,a<10&&(a="0"+a),t.attr("id",e.attr("id").split("_")[0]+"_"+a),t.appendTo($("#product-form"));var i="#"+t.attr("id"),o=$(i+" .save-button"),n=$(i+" .typeahead"),s=$(i+" .serial-number");o.prop("disabled",!1),n.prop("disabled",!1),s.prop("disabled",!1),o.text("Save"),ge(t.attr("id"))}function $e(e){var t=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;return t.test(e)}function Se(e){var t=/^[a-zA-Z ]{2,30}$/;return t.test(e)}function ke(e){var t=/^0[0-8]\d{8}$/g;return t.test(e)}function Ee(e){var t=/^[0-9]{4}$/;return t.test(e)}function Ce(e){var t=e.split("/"),a=new Date(t[1]+"/"+t[0]+"/"+t[2]),i=new Date(2019,0,6),o=new Date(2018,9,15);return console.log(a),console.log(i),console.log(o),"Invalid Date"==a?(console.log("not a date, returning false"),!1):a>=o&&a<=i}function Ie(e){return""!=e&&e.length>1}function Pe(e){return!!e&&(!(e.length&&e.length<1)&&e.length>1)}function Ne(e,t){return"OTHER*"!=t||""!=e&&e.length>1}function Te(e){if(console.log("****"),console.log(e),console.log(e.length),!e)return!1;if(!e.length&&e.length<1)return!1;if(0===e.length)return!1;for(var t=e.length,a=0,i=[],o=0;o<t;o++){if(e[o].Name.length>0&&e[o].SerialNumber.length>0&&a++,i.indexOf(e[o].SerialNumber.toLowerCase())>=0)return!1;i.push(e[o].SerialNumber.toLowerCase())}return t===a}function Me(){function e(){t.find("input").on("blur focus",function(e){"focus"===e.type&&($(this).removeClass("error"),$(this).next().is(".form-feedback, .error")&&$(this).next().removeClass("error")),"blur"===e.type&&"required"==$(this).attr("required")&&$(this).val().length<1&&$(this).next().is(".form-feedback")&&($(this).addClass("error"),$(this).next().addClass("error").find("span").text(a))})}var t=$(".fm01"),a="This field is required";return{_init:function(t){e()}}}function xe(){function e(){t(),$scope.find(".tile--110 .onoffswitch-checkbox").change(function(){t(),$(this).prop("checked")?a($(this)):(n=$(this),i())}),$scope.find(".modal .field.buttons").on("click","button",function(){o()})}function t(){$scope.find(".tile--110 .onoffswitch-checkbox").each(function(e,t){$(this).parent().parent().find(".heading").text($(this).prop("checked")?"Unsubscribe to this:":"Subscribe to this:")})}function a(e){$("body").append('<div class="mc08a unsubscribe"><span class="icon-svg-tick-circle"></span>Thank you, you have successfully subscribed.</div>');var t=new TimelineMax;t.fromTo($(".mc08a.unsubscribe"),.35,{css:{opacity:0}},{css:{opacity:1}}),t.to($(".mc08a.unsubscribe"),.35,{css:{opacity:0},delay:2,autoAlpha:0,onComplete:function(){$(".mc08a.unsubscribe").remove()}})}function i(){$scope.find(".modal").removeClass("hide--me"),TweenMax.fromTo($scope.find(".modal"),.35,{css:{scale:0}},{css:{scale:1}}),$scope.find(".modal").off("click"),$scope.find(".modal").on("click",function(e){($(e.target).hasClass("modal")||$(e.target).hasClass("max-788"))&&($scope.find(".modal").off("click"),o())})}function o(){TweenMax.fromTo($scope.find(".modal"),.35,{css:{scale:1}},{css:{scale:0},onComplete:function(){$scope.find(".modal").addClass("hide--me")}})}$scope=$(".mc08a");var n;return{_init:function(){e()}}}function Le(){var e=$("#firstName").val(),t=$("#email").val(),a=$("#stateOrTerritory").val(),i=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;t&&(t=i.test(String(t).toLowerCase()));var o=grecaptcha.getResponse(),n=0!==o.length;n||(n=!1),$("#firstNameValidationMessage.field-validation-valid").css("display",e?"none":"block"),$("#emailValidationMessage.field-validation-valid").css("display",t?"none":"block"),$("#stateValidationMessage.field-validation-valid").css("display",a?"none":"block"),$("#recaptchaValidationMessage").css("display",n?"none":"block");var s=e&&t&&a&&n;s&&Ae(!0)}function Ae(e){e?$("#thankyou-message").css("display","block"):$("#thankyou-message").css("display","none")}function _e(){$("#submit-subscribe-form").on("click",function(){Le()})}var De=500,Re=500,je=null,Oe=null,Be=!1;$(".cd-dropdown-trigger").hover(function(t){t.preventDefault(),e(this,De)},function(e){e.preventDefault(),t(Re)}),$(".nav-grid").hover(function(e){null!=Oe&&(clearTimeout(Oe),Oe=null)},function(e){t(Re)}),$(".cd-dropdown-trigger").click(function(a){return a.preventDefault(),Be?void t(0):void e(this,0)});var Ge,Ue=!1;$("#menu-button").on("click",function(e){e.preventDefault(),$("#mobile-menu").show(),$("#close-button").show(),$("#menu-button").hide(),$("html, body").css({overflow:"hidden",height:"100%"})}),$("#close-button, #mobile-menu").on("click",function(e){e.preventDefault(),$("#mobile-menu").hide(),$("#close-button").hide(),$("#menu-button").show(),$("html, body").css({overflow:"auto",height:"auto"})}),$("#menu-container *").on("click",function(e){e.stopPropagation()}),$(".new-user .close").on("click",function(){$(this).closest(".active").removeClass("active"),$(this).parent().remove()}),$(function(){setTimeout(function(){$(".nav.toolbar li.new-user").remove(),$(".nav.toolbar ul.sub-menu").removeClass("active")},1e4)}),$("#canon-group-companies, #close-canon-companies").on("click",function(e){$(".canon-group-companies").slideToggle()}),window.onload=function(){
const e=document.querySelectorAll(".mobile-nav>*:not(.search)"),t=document.querySelectorAll(".search"),i=document.querySelector("footer");for(var n=0;n<e.length;n++)e[n].addEventListener("click",a);for(var n=0;n<t.length;n++)t[n].addEventListener("click",o);i.addEventListener("click",a)};var Fe=!1;$(window).click(function(){return Fe?null:($(".mc2--dash__nav .nav-content.ddown-show").length>0&&$(".mc2--dash__nav .nav-content.ddown-show .mystore .ddown").trigger("click"),void s($(".cd-dropdown-trigger-v1.dropdown-is-active-v1").parent()))}),$("header,.cd-dropdown-v1,.cd-secondary-dropdown-v1").click(function(e){e.stopPropagation()}),$("#newheader .nav-l1 a").on("focus",function(e,t){$(this).parent().parent().hasClass("nav-l1")&&$(this).parentsUntil("ul").addClass("open"),$(this).parent().parent().hasClass("nav-l2")&&$(this).parentsUntil(".nav-l1").last().addClass("open"),$(this).parentsUntil("ul").parent().hasClass("nav-l3")&&($("#newheader .nav-l2 .active").removeClass("active"),$("#newheader .nav-l2 .open2").removeClass("open2"),$(this).parentsUntil(".menu-l3").last().parent().addClass("open2"),$(this).parentsUntil(".nav-l2").last().addClass("active"),$(this).parentsUntil(".nav-l1").last().addClass("open"))}),$("#newheader ul.nav-l1 a").on("blur",function(e){n()}),$("#newheader .nav-l2").on("click","> li",function(e){$("#newheader .nav-l2 .active").removeClass("active"),$("#newheader .nav-l2 .menu-l3.open2").removeClass("open2"),$(this).find(".menu-l3").addClass("open2"),$(this).addClass("active")});var Ge;$(".nav.toolbar a:not(.search)").on("click",function(e){e.preventDefault(),$(this).siblings(".sub-menu").toggleClass("active"),$(".nav.toolbar .sub-menu").not($(this).siblings(".sub-menu")).removeClass("active")}),$(".cd-dropdown-trigger-v1").on("click",function(e){e.preventDefault(),s($(this).parent())}),$(".cd-dropdown-v1 .cd-close").on("click",function(e){e.preventDefault(),s($(this).parent())}),$(".has-children").children("a").on("click",function(e){e.preventDefault();var t=$(this);t.next("ul").removeClass("is-hidden").end().parent(".has-children").parent("ul").addClass("move-out")});var Je=$(".cd-dropdown-wrapper-v1").hasClass("open-to-left")?"left":"right";if($(".cd-dropdown-content-v1").menuAim({activate:function(e){$(e).children().addClass("is-active").removeClass("fade-out"),0==$(".cd-dropdown-content-v1 .fade-in").length&&$(e).children("ul").addClass("fade-in")},deactivate:function(e){$(e).children().removeClass("is-active"),(0==$("li.has-children:hover").length||$("li.has-children:hover").is($(e)))&&($(".cd-dropdown-content-v1").find(".fade-in").removeClass("fade-in"),$(e).children("ul").addClass("fade-out"))},exitMenu:function(){return $(".cd-dropdown-content-v1").find(".is-active").removeClass("is-active"),!0},submenuDirection:Je}),$(".go-back").on("click",function(){var e=$(this);$(this).parent("ul").parent(".has-children").parent("ul");e.parent("ul").addClass("is-hidden").parent(".has-children").parent("ul").removeClass("move-out")}),$(".desktop .cd-dropdown-content-v1").each(function(){$this=$(this),$this.find(".cd-secondary-dropdown-v1").each(function(e,t){$(t).css("min-height",$(t).closest(".cd-dropdown-content-v1").css("height"))})}),$(".new-user .close").on("click",function(){$(this).closest(".active").removeClass("active"),$(this).parent().remove()}),$(function(){setTimeout(function(){$(".nav.toolbar li.new-user").remove(),$(".nav.toolbar ul.sub-menu").removeClass("active")},1e4)}),c(),$(".cb19 .heading").on("click",function(e){if(e.preventDefault(),$parent=$(this).parentsUntil(".container").last(),$(this).find(".active").hasClass("open"))$parent.find(".content.open").removeClass("open"),$parent.find("span.active").removeClass("active"),$parent.last().find("span:first-child").addClass("active"),$(this).find("span:first-child").removeClass("active"),$(this).closest(".item").find(".content").addClass("open");else{var t=$(this);t.find("span:first-child").addClass("active"),t.closest(".item").find(".content").removeClass("open")}}),$(".cb15 ul.list-category  li > button, .cb15a ul.list-category  li > button").on("click",function(e){return $this=$(this),$parent=$(this).parentsUntil($("ul.list-category")).last(),$this.parent().attr("data-url")&&""!=$this.parent().attr("data-url")?(document.location=$this.parent().attr("data-url"),null):($this.find(".active").hasClass("open")?($('div[class*="cb15"] ul.list-category .item.open').each(function(e){$(this).find("span.open").addClass("active"),$(this).find("span.close").removeClass("active"),$(this).find(".content.open").removeClass("open"),$(this).removeClass("open")}),$this.parent().addClass("open").find(".content").addClass("open")):$this.parent().removeClass("open").find(".content").removeClass("open"),void $this.find("span.open, span.close").toggleClass("active"))}),$(".cf05 .results-list .result").on("click",function(e){$this=$(this),$content=$this.find(".expanded"),$content.hasClass("active")?$(".cf05 .expanded.active").removeClass("active"):($(".cf05 .expanded.active").removeClass("active"),$content.addClass("active"))}).children().click(function(e){if(!$(e.target).is("input"))return!1}),$(".gl02 .footer-accordion > li > a").on("click",function(e){e.preventDefault(),$(this).hasClass("active")?$(".gl02 .footer-accordion > li > a").removeClass("active"):($(".gl02 .footer-accordion > li > a").removeClass("active"),$(this).addClass("active"))}),$(".new-accordion .outer-item > .container").on("click",function(e){var t=$(".gl01").height(),a=$(this);e.preventDefault(),$(this).parent().hasClass("active")?$(".new-accordion .outer-item.active").removeClass("active").find(".lower").one("transitionend",function(){var e=a.offset().top-10-t;$("html,body").animate({scrollTop:e},"slow")}):($(".new-accordion .outer-item.active").removeClass("active").find(".lower").one("transitionend",function(){var e=a.offset().top-10-t;$("html,body").animate({scrollTop:e},"slow")}),$(this).parent().addClass("active").find(".lower").one("transitionend",function(){var e=a.offset().top-10-t;$("html,body").animate({scrollTop:e},"slow")}))}),$(".cl01 .selector").on("click","button",function(e){$(this).parent().find("button").toggleClass("active"),$(this).parentsUntil(".cl01").parent().toggleClass("list")}),$(".has-subnav a").on("focus blur",function(e){"blur"!=e.type?$(this).closest(".has-subnav").addClass("active"):$(this).closest(".has-subnav").removeClass("active")}),$(".has-subnav").on("touchstart",function(e){$(this).toggleClass("active"),$(document).on("click",function(e){$(e.target).is(".has-subnav")||$(".has-subnav").removeClass("active").trigger("blur")})}),"undefined"!=typeof addthis)try{setTimeout(function(){$(".addthis_sharing_toolbox").attr("id","share"),$('.addthis_sharing_toolbox a[tabindex="1"]').attr("tabindex","0"),$('[class*="addthis_inline_share"] a[tabindex="1"]').attr("tabindex","0")},2500)}catch(Ye){console.warn("addthis tabindex error")}var He=function(){function e(){t=$(window).scrollTop(),t>$(".sticknav").attr("data-top")?($(".sticknav").addClass("sticky--fixed"),$(".sticknav .line")):$(".sticknav").removeClass("sticky--fixed")}var t=0;$(window).height(),$(document).height();return{_init:function(){$("div.sticknav").each(function(){$(this).attr("data-top",Math.max($(this).position().top,$(this).offset().top))}),$("div.sticknav").length<1&&$(".gl01").addClass("stickpos sticknav sticky--fixed").attr("data-top","0"),$(".sticknav.stickpos").append('<div class="line"></div>'),e()},_refresh:function(){e()}}},We=He();We._init(),$(window).on("scroll",$.throttle(280,We._refresh));var ze=function(){return{_init:function(){$('a[href^="#"]').each(function(e,t){$this=$(this),ref=$this.attr("href"),ref.length>2&&$(ref).length>0&&$this.on("click",function(e,t){$('a[href^="#"].hashtag-active').removeClass("hashtag-active"),$(this).addClass("hashtag-active"),event.preventDefault(),ref=$(this).attr("href"),topY=$(ref).offset().top,console.log("click",ref,topY),window.scrollTo({top:topY+50,behavior:"smooth"})})})}}},Xe=ze();Xe._init();var qe=function(){var e=200;return{_init:function(){$("body").prepend('<a href="#" class="back-to-top"></a>'),$(window).scroll(function(){$(window).scrollTop()>e?$("a.back-to-top").fadeIn("slow"):$("a.back-to-top").fadeOut("slow")}),$("a.back-to-top").on("click",function(e){e.preventDefault(),$("html,body").animate({scrollTop:0},"slow")})}}},Ve=qe();Ve._init(),$(".nv10b .heading").on("click",function(){$(".nv10b").toggleClass("active")}),$(".flick.carousel").flickity({lazyLoad:3,imagesLoaded:!0,cellAlign:"center"}),$(".carousel-wrap").each(function(){$imageCarousel=$(this).find(".carousel-images"),$carouselImageSlider=$(this).find(".carousel-images"),$carouselContainer=$(this).find(".carousel-container"),$imageCarousel.css({width:100*$imageCarousel.children().length+"%"}),$(this).find(".slideCount").html($imageCarousel.children().length),$(this).find(".carousel-content >div:first-child").addClass("active"),0==$carouselImageSlider.find("div").eq(0).find("img").length?$carouselContainer.find(".carousel-media").addClass("inactive"):$carouselContainer.find(".carousel-media").removeClass("inactive")});var Ke=!1;$(".carousel-btn").on("click",function(){if(!Ke){var e=$(this).closest(".carousel-wrap"),t=parseInt(e.find(".currSlide").text()),a=parseInt(e.find(".slideCount").text()),i="next"==this.id;(t>=1&&t<a&&i||t>1&&t<=a&&!i)&&p(e,i,t)}}),$(".cbbs.carousel").slick({infinite:!1,slidesToShow:3,slidesToScroll:1,centerMode:!1,nextArrow:"<a class='icomoon-ArrowRight btn slick-next'></a>",prevArrow:"<a class='icomoon-ArrowLeft btn slick-prev'></a>",responsive:[{breakpoint:700,settings:{slidesToShow:1,slidesToScroll:1}}]});h().q;String.prototype.replaceAll=function(e,t){return this.replace(new RegExp(e,"g"),t)};var Qe=4;$(".cb15 .options").on("click","button",function(e){$cat=$(this).attr("data-type"),$this=$(this),$this.hasClass("selected")||$(".cb15 .options button.selected").removeClass("selected"),$this.toggleClass("selected"),$this.hasClass("selected")?($(".cb15 .step2-heading").removeClass("opac"),$(".cb15 .layout--color").addClass("open"),TweenMax.to($(window),1,{scrollTo:{y:$(".cb15 .step2-heading").offset().top-65,offsetY:50,autoKill:!0},ease:Power3.easeOut}),"driver"===$cat?($(".cb15 .list-category li.has-driver").removeClass("hide").addClass("show"),$(".cb15 .list-category li:not(.has-driver)").removeClass("show").addClass("hide")):$(".cb15 .list-category li").removeClass("hide").addClass("show"),"repair"==$cat?($(".cb15 .noservice").addClass("hidden"),$(".cb15 .head--5.selected").text("You have selected "+$this.attr("data-label")+", now choose the type of product.")):($(".cb15 .noservice").removeClass("hidden"),$(".cb15 .head--5.selected").text("You have selected "+$this.attr("data-label")))):($(".cb15 .step2-heading").addClass("opac"),$(".cb15 .layout--color").removeClass("open")),$count=$(".cb15 .list-category > li.show").length,$count>4?($(".cb15 .more-container").removeClass("hidden"),$(".cb15 .list-category > li.show:nth-child(n+5)").addClass("hidden"),$(".cb15 .more-container button span:last-child ").text("("+($count-Qe)+" product categories left)")):$(".cb15 .more-container").addClass("hidden")}),$(".cb15 .more-container button").on("click",function(e){$(".cb15 .list-category > li.hidden").removeClass("hidden"),$(".cb15 .more-container").addClass("hidden")}),$(".ff04 input[type='radio']").on("change",function(){$(".ff04 .section").removeClass("active"),$checkedSection=$(this).data("section"),$("#"+$checkedSection).addClass("active")}),$(".cb15a .options").on("click","button",function(e){$cat=$(this).attr("data-type"),$this=$(this),$this.hasClass("selected")||$(".cb15a .options button.selected").removeClass("selected"),$this.toggleClass("selected"),$this.hasClass("selected")?($(".cb15a .step2-heading").removeClass("opac"),$(".cb15a .layout--color").addClass("open"),$(".cb15a .support-section").removeClass("selected"),$(".cb15a #"+$this.data("type")).addClass("selected"),TweenMax.to($(window),1,{scrollTo:{y:$(".cb15a .step2-heading").offset().top-65,offsetY:50,autoKill:!0},ease:Power3.easeOut})):($(".cb15a .step2-heading").addClass("opac"),$(".cb15a .layout--color").removeClass("open"))}),f();var Ze=[{destination:"RUSSIA and THE BALTICS"},{destination:"CANADA"},{destination:"EGYPT and JORDAN"},{destination:"ICELAND"},{destination:"INDIA"},{destination:"JAPAN"},{destination:"LAPLAND"},{destination:"MADAGASCAR"},{destination:"MOROCCO"},{destination:"PERU"}],et=[{image:"https://www.canon.com.au/~/media/Images/christmas/canada",title:"CANADA",subtitle1:"Go wild with the family in pristine wilderness",subtitle2:"8 -19 July 2019",subtitle3:"2 Adults & 2 Children under 12",brochure:"https://www.canon.com.au/~/media/Images/christmas/canada-Itinerary.pdf",litebox:[{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Canada/Canada-1.jpg",title:"CANADA",description:"<br><p>Introduce the family to rugged landscapes, wicked adventure and the friendliest people on earth. Hitch a ride on a helicopter, train, cruiser and even horses through breath-taking canyons, glaciers, icefields, waterfalls, lakes and forests. It’s action-packed family adventure all the way.<p><ul><li>Speed through Grand Howe Sound in Vancouver on a sea safari to spot seals and sea eagles</li><li>Zipline through mountain treetops in Whistler</li><li>Take a Bear Tour and canoe the world-renowned River of Golden Dreams</li><li>Ride the Rocky Mountaineer through majestic mountains and valleys</li></ul><br>",photoBy:"Photograph by Tony Irving (@tony.irving)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Canada/Canada-2.jpg",title:"CANADA",description:"<ul><li>Stay in the famous mountain playgrounds of Jasper and Banff</li><li>Ride the Ice Explorer on a Glacier tour of the Columbian Icefields</li><li>Immerse yourself in the turquoise waters of Lake Louise in Banff</li><li>See the ‘Matterhorn’ of the Canadian Rockies from above with a  helicopter tour of Mt Assiniboine</li></ul><center><p><b>12 Day Family Tour</b><br>8-19 July 2019<br>2 Adults & 2 Children under 12<br>Curated Tour – Total 4 families (16 people)</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners </b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Tony Irving (@tony.irving)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Canada/Canada-3.jpg",title:"CANADA",description:"<ul><li>Stay in the famous mountain playgrounds of Jasper and Banff</li><li>Ride the Ice Explorer on a Glacier tour of the Columbian Icefields</li><li>Immerse yourself in the turquoise waters of Lake Louise in Banff</li><li>See the ‘Matterhorn’ of the Canadian Rockies from above with a  helicopter tour of Mt Assiniboine</li></ul><center><p><b>12 Day Family Tour</b><br>8-19 July 2019<br>2 Adults & 2 Children under 12<br>Curated Tour – Total 4 families (16 people)</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners </b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Tony Irving (@tony.irving)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Canada/Canada-4.jpg",title:"CANADA",description:"<ul><li>Stay in the famous mountain playgrounds of Jasper and Banff</li><li>Ride the Ice Explorer on a Glacier tour of the Columbian Icefields</li><li>Immerse yourself in the turquoise waters of Lake Louise in Banff</li><li>See the ‘Matterhorn’ of the Canadian Rockies from above with a  helicopter tour of Mt Assiniboine</li></ul><center><p><b>12 Day Family Tour</b><br>8-19 July 2019<br>2 Adults & 2 Children under 12<br>Curated Tour – Total 4 families (16 people)</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners </b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Tony Irving (@tony.irving)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Canada/Canada-5.jpg",title:"CANADA",description:"<ul><li>Stay in the famous mountain playgrounds of Jasper and Banff</li><li>Ride the Ice Explorer on a Glacier tour of the Columbian Icefields</li><li>Immerse yourself in the turquoise waters of Lake Louise in Banff</li><li>See the ‘Matterhorn’ of the Canadian Rockies from above with a  helicopter tour of Mt Assiniboine</li></ul><center><p><b>12 Day Family Tour</b><br>8-19 July 2019<br>2 Adults & 2 Children under 12<br>Curated Tour – Total 4 families (16 people)</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners </b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Tony Irving (@tony.irving)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Canada/Canada-6.jpg",title:"CANADA",description:"<ul><li>Stay in the famous mountain playgrounds of Jasper and Banff</li><li>Ride the Ice Explorer on a Glacier tour of the Columbian Icefields</li><li>Immerse yourself in the turquoise waters of Lake Louise in Banff</li><li>See the ‘Matterhorn’ of the Canadian Rockies from above with a  helicopter tour of Mt Assiniboine</li></ul><center><p><b>12 Day Family Tour</b><br>8-19 July 2019<br>2 Adults & 2 Children under 12<br>Curated Tour – Total 4 families (16 people)</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners </b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Tony Irving (@tony.irving)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Canada/Canada-7.jpg",title:"CANADA",description:"<ul><li>Stay in the famous mountain playgrounds of Jasper and Banff</li><li>Ride the Ice Explorer on a Glacier tour of the Columbian Icefields</li><li>Immerse yourself in the turquoise waters of Lake Louise in Banff</li><li>See the ‘Matterhorn’ of the Canadian Rockies from above with a  helicopter tour of Mt Assiniboine</li></ul><center><p><b>12 Day Family Tour</b><br>8-19 July 2019<br>2 Adults & 2 Children under 12<br>Curated Tour – Total 4 families (16 people)</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners </b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Tony Irving (@tony.irving)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Canada/Canada-8.jpg",title:"CANADA",description:"<ul><li>Stay in the famous mountain playgrounds of Jasper and Banff</li><li>Ride the Ice Explorer on a Glacier tour of the Columbian Icefields</li><li>Immerse yourself in the turquoise waters of Lake Louise in Banff</li><li>See the ‘Matterhorn’ of the Canadian Rockies from above with a  helicopter tour of Mt Assiniboine</li></ul><center><p><b>12 Day Family Tour</b><br>8-19 July 2019<br>2 Adults & 2 Children under 12<br>Curated Tour – Total 4 families (16 people)</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners </b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Tony Irving (@tony.irving)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Canada/Canada-9.jpg",title:"CANADA",description:"<ul><li>Stay in the famous mountain playgrounds of Jasper and Banff</li><li>Ride the Ice Explorer on a Glacier tour of the Columbian Icefields</li><li>Immerse yourself in the turquoise waters of Lake Louise in Banff</li><li>See the ‘Matterhorn’ of the Canadian Rockies from above with a  helicopter tour of Mt Assiniboine</li></ul><center><p><b>12 Day Family Tour</b><br>8-19 July 2019<br>2 Adults & 2 Children under 12<br>Curated Tour – Total 4 families (16 people)</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners </b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Tony Irving (@tony.irving)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Canada/Canada-10.jpg",title:"CANADA",description:"<ul><li>Stay in the famous mountain playgrounds of Jasper and Banff</li><li>Ride the Ice Explorer on a Glacier tour of the Columbian Icefields</li><li>Immerse yourself in the turquoise waters of Lake Louise in Banff</li><li>See the ‘Matterhorn’ of the Canadian Rockies from above with a  helicopter tour of Mt Assiniboine</li></ul><center><p><b>12 Day Family Tour</b><br>8-19 July 2019<br>2 Adults & 2 Children under 12<br>Curated Tour – Total 4 families (16 people)</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners </b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Tony Irving (@tony.irving)"}]},{image:"https://www.canon.com.au/~/media/Images/christmas/egypt",title:"EGYPT and JORDAN",subtitle1:"Step back in time for a private tour of the ancient wonders of the world",subtitle2:"1-16 November 2019",subtitle3:"2 People",brochure:"https://www.canon.com.au/~/media/Images/christmas/egypt-jordan.pdf",litebox:[{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Egypt%20Jordan/Egypt-1.jpg",title:"EGYPT and JORDAN",description:"<br><p>Witness biblical lands of epic proportions through the lens of the Pharaohs and Moses. There’s a lot more to Egypt and Jordan than pyramids, the Sahara and Sphinx - and you’ll capture it all in a small tour with just four other people.<p><ul><li>Enter the ancient Wonders of the World at the Great Pyramids of Giza and the Sphinx</li><li>Live like a Bedouin and 4x4 through the Wadi Rum for a day at the Dead Sea, one of the most spectacular and spiritual landscapes in the world</li><li>Cruise the Nile in luxury to Aswan and explore 7000 years of Egyptian civilization at Karnac, the Valley of Kings and the Temple of Horus</li><li>Fly from Aswan to Abu Simbel where Ramses II’s most spectacular temple awaits</li></ul>",photoBy:"Photograph by Jona Grey (@jonagrey)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Egypt%20Jordan/Egypt-2.jpg",title:"EGYPT and JORDAN",description:"<ul><li>Visit the narrow, twisting passages of the ancient Khan El Khalili Bazaar with its intoxicating aromas and craftsmen displaying wares and skills  passed down for generations</li><li>To Amman and the ancient Roman city of Jerash, Mt Nebo where Moses  was buried, Bethany, where John the Baptist lived and Madaba, a city of spectacular Byzantine mosaics</li></ul><center><p><b>16 Days </b><br>2 People<br>1-16 November 2019<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Jona Grey (@jonagrey)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Egypt%20Jordan/Egypt-3.jpg",title:"EGYPT and JORDAN",description:"<ul><li>Visit the narrow, twisting passages of the ancient Khan El Khalili Bazaar with its intoxicating aromas and craftsmen displaying wares and skills  passed down for generations</li><li>To Amman and the ancient Roman city of Jerash, Mt Nebo where Moses  was buried, Bethany, where John the Baptist lived and Madaba, a city of spectacular Byzantine mosaics</li></ul><center><p><b>16 Days </b><br>2 People<br>1-16 November 2019<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Jona Grey (@jonagrey)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Egypt%20Jordan/Egypt-4.jpg",title:"EGYPT and JORDAN",description:"<ul><li>Visit the narrow, twisting passages of the ancient Khan El Khalili Bazaar with its intoxicating aromas and craftsmen displaying wares and skills  passed down for generations</li><li>To Amman and the ancient Roman city of Jerash, Mt Nebo where Moses  was buried, Bethany, where John the Baptist lived and Madaba, a city of spectacular Byzantine mosaics</li></ul><center><p><b>16 Days </b><br>2 People<br>1-16 November 2019<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Jona Grey (@jonagrey)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Egypt%20Jordan/Egypt-5.jpg",title:"EGYPT and JORDAN",description:"<ul><li>Visit the narrow, twisting passages of the ancient Khan El Khalili Bazaar with its intoxicating aromas and craftsmen displaying wares and skills  passed down for generations</li><li>To Amman and the ancient Roman city of Jerash, Mt Nebo where Moses  was buried, Bethany, where John the Baptist lived and Madaba, a city of spectacular Byzantine mosaics</li></ul><center><p><b>16 Days </b><br>2 People<br>1-16 November 2019<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Jona Grey (@jonagrey)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Egypt%20Jordan/Jordan-1.jpg",title:"EGYPT and JORDAN",description:"<ul><li>Visit the narrow, twisting passages of the ancient Khan El Khalili Bazaar with its intoxicating aromas and craftsmen displaying wares and skills  passed down for generations</li><li>To Amman and the ancient Roman city of Jerash, Mt Nebo where Moses  was buried, Bethany, where John the Baptist lived and Madaba, a city of spectacular Byzantine mosaics</li></ul><center><p><b>16 Days </b><br>2 People<br>1-16 November 2019<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Jona Grey (@jonagrey)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Egypt%20Jordan/Jordan-2.jpg",title:"EGYPT and JORDAN",description:"<ul><li>Visit the narrow, twisting passages of the ancient Khan El Khalili Bazaar with its intoxicating aromas and craftsmen displaying wares and skills  passed down for generations</li><li>To Amman and the ancient Roman city of Jerash, Mt Nebo where Moses  was buried, Bethany, where John the Baptist lived and Madaba, a city of spectacular Byzantine mosaics</li></ul><center><p><b>16 Days </b><br>2 People<br>1-16 November 2019<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Jona Grey (@jonagrey)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Egypt%20Jordan/Jordan-3.jpg",title:"EGYPT and JORDAN",description:"<ul><li>Visit the narrow, twisting passages of the ancient Khan El Khalili Bazaar with its intoxicating aromas and craftsmen displaying wares and skills  passed down for generations</li><li>To Amman and the ancient Roman city of Jerash, Mt Nebo where Moses  was buried, Bethany, where John the Baptist lived and Madaba, a city of spectacular Byzantine mosaics</li></ul><center><p><b>16 Days </b><br>2 People<br>1-16 November 2019<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Jona Grey (@jonagrey)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Egypt%20Jordan/Jordan-4.jpg",title:"EGYPT and JORDAN",description:"<ul><li>Visit the narrow, twisting passages of the ancient Khan El Khalili Bazaar with its intoxicating aromas and craftsmen displaying wares and skills  passed down for generations</li><li>To Amman and the ancient Roman city of Jerash, Mt Nebo where Moses  was buried, Bethany, where John the Baptist lived and Madaba, a city of spectacular Byzantine mosaics</li></ul><center><p><b>16 Days </b><br>2 People<br>1-16 November 2019<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Jona Grey (@jonagrey)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Egypt%20Jordan/Jordan-5.jpg",title:"EGYPT and JORDAN",description:"<ul><li>Visit the narrow, twisting passages of the ancient Khan El Khalili Bazaar with its intoxicating aromas and craftsmen displaying wares and skills  passed down for generations</li><li>To Amman and the ancient Roman city of Jerash, Mt Nebo where Moses  was buried, Bethany, where John the Baptist lived and Madaba, a city of spectacular Byzantine mosaics</li></ul><center><p><b>16 Days </b><br>2 People<br>1-16 November 2019<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Jona Grey (@jonagrey)"}]},{image:"https://www.canon.com.au/~/media/Images/christmas/iceland",title:"ICELAND",subtitle1:"Get up close and personal in a land of Vikings and Volcanoes, Hot Springs and Ice Glaciers",subtitle2:"24 July – 2 August 2019",subtitle3:"2 People",brochure:"https://www.canon.com.au/~/media/Images/christmas/iceland-itinerary.pdf",litebox:[{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Iceland/Iceland-1.jpg",title:"ICELAND",description:"<br><p>Get right in the frame with just four other people in the rugged beauty and raw power that is Iceland. Soak in the hot springs, nudge up against glaciers and experience at close hand rugged landscapes of fire and ice<p><ul><li>Take a private tour across ancient lava fields to the majestic Blue Lagoon</li><li>Trek a National Park, where you actually walk between two continents on the North American and Eurasian tectonic plates</li><li>Cross a rugged mountain pass to cascades of towering waterfalls, hot springs powerful geysers</li><li>Visit the home of Viking pioneers and Icelandic Sagas – just 100kms from the Arctic Circle</li></ul>",photoBy:"Photograph by Stephanie Vella (@steph_vella)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Iceland/Iceland-2.jpg",title:"ICELAND",description:"<ul><li>Pass bubbling hot mud pools, fjords and volcanic craters to Dettifloss, the mightiest waterfall in Europe</li><li>Photograph Fjords and the largest Glacier in Europe</li><li>Cruise the Glacier Lagoon where icebergs collide in icy blue waters</li><li>See the Golden Waterfall of Gullfoss, a 30m geyser eruption and countless crystal-clear bubbling hot springs before trip home with your own Icelandic Saga to remember</li></ul><center><p><b>10 Days </b><br>24 July-2 August 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Stephanie Vella (@steph_vella)"
},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Iceland/Iceland-3.jpg",title:"ICELAND",description:"<ul><li>Pass bubbling hot mud pools, fjords and volcanic craters to Dettifloss, the mightiest waterfall in Europe</li><li>Photograph Fjords and the largest Glacier in Europe</li><li>Cruise the Glacier Lagoon where icebergs collide in icy blue waters</li><li>See the Golden Waterfall of Gullfoss, a 30m geyser eruption and countless crystal-clear bubbling hot springs before trip home with your own Icelandic Saga to remember</li></ul><center><p><b>10 Days </b><br>24 July-2 August 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Stephanie Vella (@steph_vella)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Iceland/Iceland-4.jpg",title:"ICELAND",description:"<ul><li>Pass bubbling hot mud pools, fjords and volcanic craters to Dettifloss, the mightiest waterfall in Europe</li><li>Photograph Fjords and the largest Glacier in Europe</li><li>Cruise the Glacier Lagoon where icebergs collide in icy blue waters</li><li>See the Golden Waterfall of Gullfoss, a 30m geyser eruption and countless crystal-clear bubbling hot springs before trip home with your own Icelandic Saga to remember</li></ul><center><p><b>10 Days </b><br>24 July-2 August 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Stephanie Vella (@steph_vella)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Iceland/Iceland-5.jpg",title:"ICELAND",description:"<ul><li>Pass bubbling hot mud pools, fjords and volcanic craters to Dettifloss, the mightiest waterfall in Europe</li><li>Photograph Fjords and the largest Glacier in Europe</li><li>Cruise the Glacier Lagoon where icebergs collide in icy blue waters</li><li>See the Golden Waterfall of Gullfoss, a 30m geyser eruption and countless crystal-clear bubbling hot springs before trip home with your own Icelandic Saga to remember</li></ul><center><p><b>10 Days </b><br>24 July-2 August 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Stephanie Vella (@steph_vella)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Iceland/Iceland-6.jpg",title:"ICELAND",description:"<ul><li>Pass bubbling hot mud pools, fjords and volcanic craters to Dettifloss, the mightiest waterfall in Europe</li><li>Photograph Fjords and the largest Glacier in Europe</li><li>Cruise the Glacier Lagoon where icebergs collide in icy blue waters</li><li>See the Golden Waterfall of Gullfoss, a 30m geyser eruption and countless crystal-clear bubbling hot springs before trip home with your own Icelandic Saga to remember</li></ul><center><p><b>10 Days </b><br>24 July-2 August 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Stephanie Vella (@steph_vella)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Iceland/Iceland-7.jpg",title:"ICELAND",description:"<ul><li>Pass bubbling hot mud pools, fjords and volcanic craters to Dettifloss, the mightiest waterfall in Europe</li><li>Photograph Fjords and the largest Glacier in Europe</li><li>Cruise the Glacier Lagoon where icebergs collide in icy blue waters</li><li>See the Golden Waterfall of Gullfoss, a 30m geyser eruption and countless crystal-clear bubbling hot springs before trip home with your own Icelandic Saga to remember</li></ul><center><p><b>10 Days </b><br>24 July-2 August 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Stephanie Vella (@steph_vella)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Iceland/Iceland-8.jpg",title:"ICELAND",description:"<ul><li>Pass bubbling hot mud pools, fjords and volcanic craters to Dettifloss, the mightiest waterfall in Europe</li><li>Photograph Fjords and the largest Glacier in Europe</li><li>Cruise the Glacier Lagoon where icebergs collide in icy blue waters</li><li>See the Golden Waterfall of Gullfoss, a 30m geyser eruption and countless crystal-clear bubbling hot springs before trip home with your own Icelandic Saga to remember</li></ul><center><p><b>10 Days </b><br>24 July-2 August 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Stephanie Vella (@steph_vella)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Iceland/Iceland-9.jpg",title:"ICELAND",description:"<ul><li>Pass bubbling hot mud pools, fjords and volcanic craters to Dettifloss, the mightiest waterfall in Europe</li><li>Photograph Fjords and the largest Glacier in Europe</li><li>Cruise the Glacier Lagoon where icebergs collide in icy blue waters</li><li>See the Golden Waterfall of Gullfoss, a 30m geyser eruption and countless crystal-clear bubbling hot springs before trip home with your own Icelandic Saga to remember</li></ul><center><p><b>10 Days </b><br>24 July-2 August 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Stephanie Vella (@steph_vella)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Iceland/Iceland-10.jpg",title:"ICELAND",description:"<ul><li>Pass bubbling hot mud pools, fjords and volcanic craters to Dettifloss, the mightiest waterfall in Europe</li><li>Photograph Fjords and the largest Glacier in Europe</li><li>Cruise the Glacier Lagoon where icebergs collide in icy blue waters</li><li>See the Golden Waterfall of Gullfoss, a 30m geyser eruption and countless crystal-clear bubbling hot springs before trip home with your own Icelandic Saga to remember</li></ul><center><p><b>10 Days </b><br>24 July-2 August 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Stephanie Vella (@steph_vella)"}]},{image:"https://www.canon.com.au/~/media/Images/christmas/india",title:"INDIA",subtitle1:"Aim for the enchanting, bizarre and addictive – a place that will sear itself into your memory",subtitle2:"8-22 October 2019",subtitle3:"2 People",brochure:"https://www.canon.com.au/~/media/Images/christmas/india-itinerary.pdf",litebox:[{image:"https://www.canon.com.au/-/media/images/christmas/carousels/India/India-1.jpg",title:"INDIA",description:"<p>Take an intimate tour right into the raw, fragrant and mystic experience that is India. You’ll discover a gem with many facets: colourful, chaotic and bustling with life.<p><ul><li>Cycle-rickshaw through narrow lanes to the 300-year old wholesale market and experience organised chaos on a grand scale</li><li>Drink in the architectural triumphs of the Mughal Empire, the Taj Mahal, palaces and magnificent temples</li><li>Stand where The Buddha gave his first sermon in 500BC.</li><li>Sail the river Ganges and witness mesmerising spiritual ceremonies of chanting, bells and candlelight</li><li>Take a guided tour through the “Old City” bazaars and markets mingling with locals and sampling their delicacies</li></ul>",photoBy:"Photograph by Melissa Findley (@melissafindley)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/India/India-2.jpg",title:"INDIA",description:"<ul><li>Be dazzled and bewitched by golden sunsets, extravagant temples and staggering architectural delights</li><li>Sample a taste of locals’ lives in small town India and a unique culinary experience in a Palace</li><li>Recover and reflect on the golden beaches of Goa</li></ul><center><p><b>15 Days </b><br>8-22 October 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Melissa Findley (@melissafindley)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/India/India-3.jpg",title:"INDIA",description:"<ul><li>Be dazzled and bewitched by golden sunsets, extravagant temples and staggering architectural delights</li><li>Sample a taste of locals’ lives in small town India and a unique culinary experience in a Palace</li><li>Recover and reflect on the golden beaches of Goa</li></ul><center><p><b>15 Days </b><br>8-22 October 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Melissa Findley (@melissafindley)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/India/India-4.jpg",title:"INDIA",description:"<ul><li>Be dazzled and bewitched by golden sunsets, extravagant temples and staggering architectural delights</li><li>Sample a taste of locals’ lives in small town India and a unique culinary experience in a Palace</li><li>Recover and reflect on the golden beaches of Goa</li></ul><center><p><b>15 Days </b><br>8-22 October 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Melissa Findley (@melissafindley)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/India/India-5.jpg",title:"INDIA",description:"<ul><li>Be dazzled and bewitched by golden sunsets, extravagant temples and staggering architectural delights</li><li>Sample a taste of locals’ lives in small town India and a unique culinary experience in a Palace</li><li>Recover and reflect on the golden beaches of Goa</li></ul><center><p><b>15 Days </b><br>8-22 October 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Melissa Findley (@melissafindley)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/India/India-6.jpg",title:"INDIA",description:"<ul><li>Be dazzled and bewitched by golden sunsets, extravagant temples and staggering architectural delights</li><li>Sample a taste of locals’ lives in small town India and a unique culinary experience in a Palace</li><li>Recover and reflect on the golden beaches of Goa</li></ul><center><p><b>15 Days </b><br>8-22 October 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Melissa Findley (@melissafindley)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/India/India-7.jpg",title:"INDIA",description:"<ul><li>Be dazzled and bewitched by golden sunsets, extravagant temples and staggering architectural delights</li><li>Sample a taste of locals’ lives in small town India and a unique culinary experience in a Palace</li><li>Recover and reflect on the golden beaches of Goa</li></ul><center><p><b>15 Days </b><br>8-22 October 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Melissa Findley (@melissafindley)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/India/India-8.jpg",title:"INDIA",description:"<ul><li>Be dazzled and bewitched by golden sunsets, extravagant temples and staggering architectural delights</li><li>Sample a taste of locals’ lives in small town India and a unique culinary experience in a Palace</li><li>Recover and reflect on the golden beaches of Goa</li></ul><center><p><b>15 Days </b><br>8-22 October 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Melissa Findley (@melissafindley)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/India/India-9.jpg",title:"INDIA",description:"<ul><li>Be dazzled and bewitched by golden sunsets, extravagant temples and staggering architectural delights</li><li>Sample a taste of locals’ lives in small town India and a unique culinary experience in a Palace</li><li>Recover and reflect on the golden beaches of Goa</li></ul><center><p><b>15 Days </b><br>8-22 October 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Melissa Findley (@melissafindley)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/India/India-10.jpg",title:"INDIA",description:"<ul><li>Be dazzled and bewitched by golden sunsets, extravagant temples and staggering architectural delights</li><li>Sample a taste of locals’ lives in small town India and a unique culinary experience in a Palace</li><li>Recover and reflect on the golden beaches of Goa</li></ul><center><p><b>15 Days </b><br>8-22 October 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Melissa Findley (@melissafindley)"}]},{image:"https://www.canon.com.au/~/media/Images/christmas/japan",title:"JAPAN",subtitle1:"Family fun for everyone with Samurai, Sumo, Bullet Trains, Geishas and Disneyland",subtitle2:"9-18 September 2019",subtitle3:"2 adults & 2 children under 12",brochure:"https://www.canon.com.au/~/media/Images/christmas/japan-itinerary.pdf",litebox:[{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Japan/Japan-1.jpg",title:"JAPAN",description:"<p>From the ancient to the modern, the fascinating to downright crazy - this intimate family tour is the only way to take it all in. You’ll see it all in the traditions, the scenery, the beautiful, the bizarre – and the magic that can only be Japan.<p><ul><li>Rickshaw the mystic bamboo forest into an exotic world of temples, Geisha and Samurai Sword Masters </li><li>Join a private class in Japanese cooking (and eating!)</li><li>Learn traditional loud, fast and very exciting Taiko Drumming</li><li>Explore 8th Century Nara and a bronze Buddha statue 15m high</li></ul>",photoBy:"Photograph by Benjamin Lee (@itchban)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Japan/Japan-2.jpg",title:"JAPAN",description:"<ul><li>Meet the Sumo Master who will prepare you for a chance to fight against a real Sumo wrestler</li><li>Ride the Bullet Train to the alpine regions with traditional rural life, rice paddies and superb scenery</li><li>Explore Yokohama and Tokyo, visit a traditional teahouse and stroll the beautiful Hamarikyu gardens.</li><li>Take a Japanese Manga class before the ultimate destination: The magic and memories of Tokyo Disneyland</li></ul><center><p><b>10 Day Family Tour</b><br>9-18 September 2019<br>2 Adults & 2 Children under 12<br>Curated Tour – Total 4 families (16 people)</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, some meals</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Benjamin Lee (@itchban)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Japan/Japan-3.jpg",title:"JAPAN",description:"<ul><li>Meet the Sumo Master who will prepare you for a chance to fight against a real Sumo wrestler</li><li>Ride the Bullet Train to the alpine regions with traditional rural life, rice paddies and superb scenery</li><li>Explore Yokohama and Tokyo, visit a traditional teahouse and stroll the beautiful Hamarikyu gardens.</li><li>Take a Japanese Manga class before the ultimate destination: The magic and memories of Tokyo Disneyland</li></ul><center><p><b>10 Day Family Tour</b><br>9-18 September 2019<br>2 Adults & 2 Children under 12<br>Curated Tour – Total 4 families (16 people)</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, some meals</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Benjamin Lee (@itchban)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Japan/Japan-4.jpg",title:"JAPAN",description:"<ul><li>Meet the Sumo Master who will prepare you for a chance to fight against a real Sumo wrestler</li><li>Ride the Bullet Train to the alpine regions with traditional rural life, rice paddies and superb scenery</li><li>Explore Yokohama and Tokyo, visit a traditional teahouse and stroll the beautiful Hamarikyu gardens.</li><li>Take a Japanese Manga class before the ultimate destination: The magic and memories of Tokyo Disneyland</li></ul><center><p><b>10 Day Family Tour</b><br>9-18 September 2019<br>2 Adults & 2 Children under 12<br>Curated Tour – Total 4 families (16 people)</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, some meals</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Benjamin Lee (@itchban)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Japan/Japan-5.jpg",title:"JAPAN",description:"<ul><li>Meet the Sumo Master who will prepare you for a chance to fight against a real Sumo wrestler</li><li>Ride the Bullet Train to the alpine regions with traditional rural life, rice paddies and superb scenery</li><li>Explore Yokohama and Tokyo, visit a traditional teahouse and stroll the beautiful Hamarikyu gardens.</li><li>Take a Japanese Manga class before the ultimate destination: The magic and memories of Tokyo Disneyland</li></ul><center><p><b>10 Day Family Tour</b><br>9-18 September 2019<br>2 Adults & 2 Children under 12<br>Curated Tour – Total 4 families (16 people)</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, some meals</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Benjamin Lee (@itchban)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Japan/Japan-6.jpg",title:"JAPAN",description:"<ul><li>Meet the Sumo Master who will prepare you for a chance to fight against a real Sumo wrestler</li><li>Ride the Bullet Train to the alpine regions with traditional rural life, rice paddies and superb scenery</li><li>Explore Yokohama and Tokyo, visit a traditional teahouse and stroll the beautiful Hamarikyu gardens.</li><li>Take a Japanese Manga class before the ultimate destination: The magic and memories of Tokyo Disneyland</li></ul><center><p><b>10 Day Family Tour</b><br>9-18 September 2019<br>2 Adults & 2 Children under 12<br>Curated Tour – Total 4 families (16 people)</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, some meals</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Benjamin Lee (@itchban)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Japan/Japan-7.jpg",title:"JAPAN",description:"<ul><li>Meet the Sumo Master who will prepare you for a chance to fight against a real Sumo wrestler</li><li>Ride the Bullet Train to the alpine regions with traditional rural life, rice paddies and superb scenery</li><li>Explore Yokohama and Tokyo, visit a traditional teahouse and stroll the beautiful Hamarikyu gardens.</li><li>Take a Japanese Manga class before the ultimate destination: The magic and memories of Tokyo Disneyland</li></ul><center><p><b>10 Day Family Tour</b><br>9-18 September 2019<br>2 Adults & 2 Children under 12<br>Curated Tour – Total 4 families (16 people)</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, some meals</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Benjamin Lee (@itchban)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Japan/Japan-8.jpg",title:"JAPAN",description:"<ul><li>Meet the Sumo Master who will prepare you for a chance to fight against a real Sumo wrestler</li><li>Ride the Bullet Train to the alpine regions with traditional rural life, rice paddies and superb scenery</li><li>Explore Yokohama and Tokyo, visit a traditional teahouse and stroll the beautiful Hamarikyu gardens.</li><li>Take a Japanese Manga class before the ultimate destination: The magic and memories of Tokyo Disneyland</li></ul><center><p><b>10 Day Family Tour</b><br>9-18 September 2019<br>2 Adults & 2 Children under 12<br>Curated Tour – Total 4 families (16 people)</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, some meals</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Benjamin Lee (@itchban)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Japan/Japan-9.jpg",title:"JAPAN",description:"<ul><li>Meet the Sumo Master who will prepare you for a chance to fight against a real Sumo wrestler</li><li>Ride the Bullet Train to the alpine regions with traditional rural life, rice paddies and superb scenery</li><li>Explore Yokohama and Tokyo, visit a traditional teahouse and stroll the beautiful Hamarikyu gardens.</li><li>Take a Japanese Manga class before the ultimate destination: The magic and memories of Tokyo Disneyland</li></ul><center><p><b>10 Day Family Tour</b><br>9-18 September 2019<br>2 Adults & 2 Children under 12<br>Curated Tour – Total 4 families (16 people)</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, some meals</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Benjamin Lee (@itchban)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Japan/Japan-10.jpg",title:"JAPAN",description:"<ul><li>Meet the Sumo Master who will prepare you for a chance to fight against a real Sumo wrestler</li><li>Ride the Bullet Train to the alpine regions with traditional rural life, rice paddies and superb scenery</li><li>Explore Yokohama and Tokyo, visit a traditional teahouse and stroll the beautiful Hamarikyu gardens.</li><li>Take a Japanese Manga class before the ultimate destination: The magic and memories of Tokyo Disneyland</li></ul><center><p><b>10 Day Family Tour</b><br>9-18 September 2019<br>2 Adults & 2 Children under 12<br>Curated Tour – Total 4 families (16 people)</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, some meals</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Benjamin Lee (@itchban)"}]},{image:"https://www.canon.com.au/~/media/Images/christmas/lapland",title:"LAPLAND",subtitle1:"Treat the family to your own Winter Wonderland of Santa action, sleigh rides and mysterious Northern Lights",subtitle2:"21-30 November 2019",subtitle3:"2 Adults & 2 Children under 12",brochure:"https://www.canon.com.au/~/media/Images/christmas/lapland-itinerary.pdf",litebox:[{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Lapland/Lapland-1.jpg",title:"LAPLAND",description:"<p>Create your own family fairy tale in a land of pure wonder and delight. It’s the Arctic Christmas adventure of a lifetime with reindeer rides, husky sleds, snowmobiles, Santa’s workshop and shimmering Northern Lights.<p><ul><li>Roam the vibrant seaside city of Helsinki with its unique Nordic culture and Scandinavian style</li><li>Visit medieval Talinn and wonder at the magical Christmas Markets </li><li>See seaplanes, submarines and more at the famous maritime museum</li><li>Fly to Santa’s Arctic Circle and be licenced to drive a reindeer sleigh</li></ul>",photoBy:"Photograph by Neil Bloem (@coldxneil)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Lapland/Lapland-2.jpg",title:"LAPLAND",description:"<ul><li>Graduate from Elf School and see Santa’s actual office and workshop</li><li>Zoom on Mini-Snowmobiles and tandem ski at a remote Wilderness Lodge</li><li>Ride a Husky Safari sled through dreamy snowy scenery.</li><li>View the mystical colourful shimmers of the Northern Lights</li></ul><center><p><b>9 Day Family Tour </b><br>21-30 November 2019<br>2 Adults & 2 Children under 12<br>Curated Tour – Total 4 families (16 people)</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners </b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Neil Bloem (@coldxneil)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Lapland/Lapland-3.jpg",title:"LAPLAND",description:"<ul><li>Graduate from Elf School and see Santa’s actual office and workshop</li><li>Zoom on Mini-Snowmobiles and tandem ski at a remote Wilderness Lodge</li><li>Ride a Husky Safari sled through dreamy snowy scenery.</li><li>View the mystical colourful shimmers of the Northern Lights</li></ul><center><p><b>9 Day Family Tour </b><br>21-30 November 2019<br>2 Adults & 2 Children under 12<br>Curated Tour – Total 4 families (16 people)</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners </b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Neil Bloem (@coldxneil)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Lapland/Lapland-4.jpg",title:"LAPLAND",description:"<ul><li>Graduate from Elf School and see Santa’s actual office and workshop</li><li>Zoom on Mini-Snowmobiles and tandem ski at a remote Wilderness Lodge</li><li>Ride a Husky Safari sled through dreamy snowy scenery.</li><li>View the mystical colourful shimmers of the Northern Lights</li></ul><center><p><b>9 Day Family Tour </b><br>21-30 November 2019<br>2 Adults & 2 Children under 12<br>Curated Tour – Total 4 families (16 people)</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners </b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Neil Bloem (@coldxneil)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Lapland/Lapland-5.jpg",title:"LAPLAND",description:"<ul><li>Graduate from Elf School and see Santa’s actual office and workshop</li><li>Zoom on Mini-Snowmobiles and tandem ski at a remote Wilderness Lodge</li><li>Ride a Husky Safari sled through dreamy snowy scenery.</li><li>View the mystical colourful shimmers of the Northern Lights</li></ul><center><p><b>9 Day Family Tour </b><br>21-30 November 2019<br>2 Adults & 2 Children under 12<br>Curated Tour – Total 4 families (16 people)</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners </b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Neil Bloem (@coldxneil)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Lapland/Lapland-6.jpg",title:"LAPLAND",description:"<ul><li>Graduate from Elf School and see Santa’s actual office and workshop</li><li>Zoom on Mini-Snowmobiles and tandem ski at a remote Wilderness Lodge</li><li>Ride a Husky Safari sled through dreamy snowy scenery.</li><li>View the mystical colourful shimmers of the Northern Lights</li></ul><center><p><b>9 Day Family Tour </b><br>21-30 November 2019<br>2 Adults & 2 Children under 12<br>Curated Tour – Total 4 families (16 people)</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners </b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Neil Bloem (@coldxneil)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Lapland/Lapland-7.jpg",title:"LAPLAND",description:"<ul><li>Graduate from Elf School and see Santa’s actual office and workshop</li><li>Zoom on Mini-Snowmobiles and tandem ski at a remote Wilderness Lodge</li><li>Ride a Husky Safari sled through dreamy snowy scenery.</li><li>View the mystical colourful shimmers of the Northern Lights</li></ul><center><p><b>9 Day Family Tour </b><br>21-30 November 2019<br>2 Adults & 2 Children under 12<br>Curated Tour – Total 4 families (16 people)</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners </b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Neil Bloem (@coldxneil)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Lapland/Lapland-8.jpg",title:"LAPLAND",description:"<ul><li>Graduate from Elf School and see Santa’s actual office and workshop</li><li>Zoom on Mini-Snowmobiles and tandem ski at a remote Wilderness Lodge</li><li>Ride a Husky Safari sled through dreamy snowy scenery.</li><li>View the mystical colourful shimmers of the Northern Lights</li></ul><center><p><b>9 Day Family Tour </b><br>21-30 November 2019<br>2 Adults & 2 Children under 12<br>Curated Tour – Total 4 families (16 people)</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners </b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Neil Bloem (@coldxneil)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Lapland/Lapland-9.jpg",title:"LAPLAND",description:"<ul><li>Graduate from Elf School and see Santa’s actual office and workshop</li><li>Zoom on Mini-Snowmobiles and tandem ski at a remote Wilderness Lodge</li><li>Ride a Husky Safari sled through dreamy snowy scenery.</li><li>View the mystical colourful shimmers of the Northern Lights</li></ul><center><p><b>9 Day Family Tour </b><br>21-30 November 2019<br>2 Adults & 2 Children under 12<br>Curated Tour – Total 4 families (16 people)</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners </b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",
photoBy:"Photograph by Neil Bloem (@coldxneil)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Lapland/Lapland-10.jpg",title:"LAPLAND",description:"<ul><li>Graduate from Elf School and see Santa’s actual office and workshop</li><li>Zoom on Mini-Snowmobiles and tandem ski at a remote Wilderness Lodge</li><li>Ride a Husky Safari sled through dreamy snowy scenery.</li><li>View the mystical colourful shimmers of the Northern Lights</li></ul><center><p><b>9 Day Family Tour </b><br>21-30 November 2019<br>2 Adults & 2 Children under 12<br>Curated Tour – Total 4 families (16 people)</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners </b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Neil Bloem (@coldxneil)"}]},{image:"https://www.canon.com.au/~/media/Images/christmas/madagascar",title:"MADAGASCAR",subtitle1:"Capture a riot of unique creatures, the weird and the wonderful, on a real life &quot;Fantasy Island&quot;",subtitle2:"2-17 August 2019",subtitle3:"2 People",brochure:"https://www.canon.com.au/~/media/Images/christmas/madagascar-itinerary.pdf",litebox:[{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Madagascar/Madagascar-1.jpg",title:"MADAGASCAR",description:"<p>Join just 4 other people on a tour of unique culture where East meets West meets Africa. Spot lemurs and chameleons, rare orchids and birdlife in untamed jungle, golden beaches and the world’s most beautiful national parks<p><ul><li>Leap with lemurs amongst the luxuriant vegetation of the island’s capital</li><li>Focus on a mind-boggling variety of orchids in Andasibe Reserve and a tropical canopy filled with colourful birds.</li><li>Visit and interact with the local tribe and experience how they live off the forest</li><li>Enjoy the high of an 800-1200m National Park and its dense jungle hills, spotting chameleons and other exotic wildlife</li></ul>",photoBy:"Photograph by Jay Collier (@jaycollier)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Madagascar/Madagascar-2.jpg",title:"MADAGASCAR",description:"<ul><li>Dip into crystal clear jungle swimming holes and view the unique “Spiny Forest”</li><li>Dive and snorkel warm tropical reef waters</li><li>Cruise with whales at the place they give birth and return home with an explosion of flora and fauna memories </li></ul><center><p><b>16 Days</b><br>2-17 August 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, breakfasts and dinners</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Jay Collier (@jaycollier)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Madagascar/Madagascar-3.jpg",title:"MADAGASCAR",description:"<ul><li>Dip into crystal clear jungle swimming holes and view the unique “Spiny Forest”</li><li>Dive and snorkel warm tropical reef waters</li><li>Cruise with whales at the place they give birth and return home with an explosion of flora and fauna memories </li></ul><center><p><b>16 Days</b><br>2-17 August 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, breakfasts and dinners</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Jay Collier (@jaycollier)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Madagascar/Madagascar-4.jpg",title:"MADAGASCAR",description:"<ul><li>Dip into crystal clear jungle swimming holes and view the unique “Spiny Forest”</li><li>Dive and snorkel warm tropical reef waters</li><li>Cruise with whales at the place they give birth and return home with an explosion of flora and fauna memories </li></ul><center><p><b>16 Days</b><br>2-17 August 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, breakfasts and dinners</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Jay Collier (@jaycollier)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Madagascar/Madagascar-5.jpg",title:"MADAGASCAR",description:"<ul><li>Dip into crystal clear jungle swimming holes and view the unique “Spiny Forest”</li><li>Dive and snorkel warm tropical reef waters</li><li>Cruise with whales at the place they give birth and return home with an explosion of flora and fauna memories </li></ul><center><p><b>16 Days</b><br>2-17 August 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, breakfasts and dinners</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Jay Collier (@jaycollier)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Madagascar/Madagascar-6.jpg",title:"MADAGASCAR",description:"<ul><li>Dip into crystal clear jungle swimming holes and view the unique “Spiny Forest”</li><li>Dive and snorkel warm tropical reef waters</li><li>Cruise with whales at the place they give birth and return home with an explosion of flora and fauna memories </li></ul><center><p><b>16 Days</b><br>2-17 August 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, breakfasts and dinners</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Jay Collier (@jaycollier)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Madagascar/Madagascar-7.jpg",title:"MADAGASCAR",description:"<ul><li>Dip into crystal clear jungle swimming holes and view the unique “Spiny Forest”</li><li>Dive and snorkel warm tropical reef waters</li><li>Cruise with whales at the place they give birth and return home with an explosion of flora and fauna memories </li></ul><center><p><b>16 Days</b><br>2-17 August 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, breakfasts and dinners</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Jay Collier (@jaycollier)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Madagascar/Madagascar-8.jpg",title:"MADAGASCAR",description:"<ul><li>Dip into crystal clear jungle swimming holes and view the unique “Spiny Forest”</li><li>Dive and snorkel warm tropical reef waters</li><li>Cruise with whales at the place they give birth and return home with an explosion of flora and fauna memories </li></ul><center><p><b>16 Days</b><br>2-17 August 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, breakfasts and dinners</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Jay Collier (@jaycollier)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Madagascar/Madagascar-9.jpg",title:"MADAGASCAR",description:"<ul><li>Dip into crystal clear jungle swimming holes and view the unique “Spiny Forest”</li><li>Dive and snorkel warm tropical reef waters</li><li>Cruise with whales at the place they give birth and return home with an explosion of flora and fauna memories </li></ul><center><p><b>16 Days</b><br>2-17 August 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, breakfasts and dinners</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Jay Collier (@jaycollier)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Madagascar/Madagascar-10.jpg",title:"MADAGASCAR",description:"<ul><li>Dip into crystal clear jungle swimming holes and view the unique “Spiny Forest”</li><li>Dive and snorkel warm tropical reef waters</li><li>Cruise with whales at the place they give birth and return home with an explosion of flora and fauna memories </li></ul><center><p><b>16 Days</b><br>2-17 August 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, breakfasts and dinners</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Jay Collier (@jaycollier)"}]},{image:"https://www.canon.com.au/&#126;/media/Images/christmas/morocco",title:"MOROCCO",subtitle1:"A romantic getaway to a land of souks and sand dunes where the Sahara meets the sea",subtitle2:"2-13 October 2019",subtitle3:"2 People",brochure:"https://www.canon.com.au/~/media/Images/christmas/morocco-itinerary.pdf",litebox:[{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Morocco/Morocco-1.jpg",title:"MOROCCO",description:"<p>Come to the Kasbah, drink at Rick’s Casablanca and discover exotic delights at every turn in the alleyways of vibrant culture, exotic fragrances and treasure-filled bazaars.<p><ul><li>Drop in to Rick’s Café at Casablanca, a recreation of the movie’s iconic bar</li><li>Meet colourful characters in the Central Market, an explosion of aromas, spices and spruiking of exotic wares </li><li>Visit an isolated town of striking blue and whitewashed homes, nestled between twin peaks of the majestic Rif Mountains</li><li>Descend from the hills to a sacred town and a visit to the remains of a Roman city and its many intact mosaics</li><li>Lose yourself in the bustling, noisy and overwhelming feast of the senses that is Fes and its aromatic Modena</li></ul>",photoBy:"Photograph by Brook Rushton (@brookrushtonfoto)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Morocco/Morocco-2.jpg",title:"MOROCCO",description:"<ul><li>Camp out like a Bedouin under desert stars in Sahara dunes a stunning 150m high</li><li>Explore souks and Berber villages, meeting locals for a home-cooked meal</li><li>Meet at the Kasbah and ride to Marrakech where snake-charmers, performers and storytellers vie with the world’s most delicious food for your attention.</li><li>Return with sights, sounds and fragrant sensations to fill your senses forever</li></ul><center><p><b>12 Days </b><br>2-13 October 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Brook Rushton (@brookrushtonfoto)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Morocco/Morocco-3.jpg",title:"MOROCCO",description:"<ul><li>Camp out like a Bedouin under desert stars in Sahara dunes a stunning 150m high</li><li>Explore souks and Berber villages, meeting locals for a home-cooked meal</li><li>Meet at the Kasbah and ride to Marrakech where snake-charmers, performers and storytellers vie with the world’s most delicious food for your attention.</li><li>Return with sights, sounds and fragrant sensations to fill your senses forever</li></ul><center><p><b>12 Days </b><br>2-13 October 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Brook Rushton (@brookrushtonfoto)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Morocco/Morocco-4.jpg",title:"MOROCCO",description:"<ul><li>Camp out like a Bedouin under desert stars in Sahara dunes a stunning 150m high</li><li>Explore souks and Berber villages, meeting locals for a home-cooked meal</li><li>Meet at the Kasbah and ride to Marrakech where snake-charmers, performers and storytellers vie with the world’s most delicious food for your attention.</li><li>Return with sights, sounds and fragrant sensations to fill your senses forever</li></ul><center><p><b>12 Days </b><br>2-13 October 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Brook Rushton (@brookrushtonfoto)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Morocco/Morocco-5.jpg",title:"MOROCCO",description:"<ul><li>Camp out like a Bedouin under desert stars in Sahara dunes a stunning 150m high</li><li>Explore souks and Berber villages, meeting locals for a home-cooked meal</li><li>Meet at the Kasbah and ride to Marrakech where snake-charmers, performers and storytellers vie with the world’s most delicious food for your attention.</li><li>Return with sights, sounds and fragrant sensations to fill your senses forever</li></ul><center><p><b>12 Days </b><br>2-13 October 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Brook Rushton (@brookrushtonfoto)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Morocco/Morocco-6.jpg",title:"MOROCCO",description:"<ul><li>Camp out like a Bedouin under desert stars in Sahara dunes a stunning 150m high</li><li>Explore souks and Berber villages, meeting locals for a home-cooked meal</li><li>Meet at the Kasbah and ride to Marrakech where snake-charmers, performers and storytellers vie with the world’s most delicious food for your attention.</li><li>Return with sights, sounds and fragrant sensations to fill your senses forever</li></ul><center><p><b>12 Days </b><br>2-13 October 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Brook Rushton (@brookrushtonfoto)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Morocco/Morocco-7.jpg",title:"MOROCCO",description:"<ul><li>Camp out like a Bedouin under desert stars in Sahara dunes a stunning 150m high</li><li>Explore souks and Berber villages, meeting locals for a home-cooked meal</li><li>Meet at the Kasbah and ride to Marrakech where snake-charmers, performers and storytellers vie with the world’s most delicious food for your attention.</li><li>Return with sights, sounds and fragrant sensations to fill your senses forever</li></ul><center><p><b>12 Days </b><br>2-13 October 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Brook Rushton (@brookrushtonfoto)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Morocco/Morocco-8.jpg",title:"MOROCCO",description:"<ul><li>Camp out like a Bedouin under desert stars in Sahara dunes a stunning 150m high</li><li>Explore souks and Berber villages, meeting locals for a home-cooked meal</li><li>Meet at the Kasbah and ride to Marrakech where snake-charmers, performers and storytellers vie with the world’s most delicious food for your attention.</li><li>Return with sights, sounds and fragrant sensations to fill your senses forever</li></ul><center><p><b>12 Days </b><br>2-13 October 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Brook Rushton (@brookrushtonfoto)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Morocco/Morocco-9.jpg",title:"MOROCCO",description:"<ul><li>Camp out like a Bedouin under desert stars in Sahara dunes a stunning 150m high</li><li>Explore souks and Berber villages, meeting locals for a home-cooked meal</li><li>Meet at the Kasbah and ride to Marrakech where snake-charmers, performers and storytellers vie with the world’s most delicious food for your attention.</li><li>Return with sights, sounds and fragrant sensations to fill your senses forever</li></ul><center><p><b>12 Days </b><br>2-13 October 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Brook Rushton (@brookrushtonfoto)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Morocco/Morocco-10.jpg",title:"MOROCCO",description:"<ul><li>Camp out like a Bedouin under desert stars in Sahara dunes a stunning 150m high</li><li>Explore souks and Berber villages, meeting locals for a home-cooked meal</li><li>Meet at the Kasbah and ride to Marrakech where snake-charmers, performers and storytellers vie with the world’s most delicious food for your attention.</li><li>Return with sights, sounds and fragrant sensations to fill your senses forever</li></ul><center><p><b>12 Days </b><br>2-13 October 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Brook Rushton (@brookrushtonfoto)"}]},{image:"https://www.canon.com.au/~/media/Images/christmas/peru",title:"PERU",subtitle1:"An intimate tour of the Amazon, the Andes and a mystic ancient empire",subtitle2:"30 August – 10 September 2019",subtitle3:"2 People",brochure:"https://www.canon.com.au/~/media/Images/christmas/peru-itinerary.pdf",litebox:[{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Peru/peru-1.jpg",title:"PERU",description:"<p>A land of untold riches and photo opportunities is here for the taking with majestic rainforests, towering mountains, and the colourful culture of a civilization that can still trace their ancient bloodlines to the Incas.<p><ul><li>Cruise the legendary Amazon, with stops for rainforest walks and a swim with pink dolphins</li><li>Go on safari spotting exotic nocturnal wildlife and caiman crocodiles</li><li>Join small tours to find macaws, toucans, monkeys and capybaras and fish for the dreaded (but very delicious) piranha</li><li>Enter the Sacred Valley at Cusco and its colossal Inca fortress</li></ul>",photoBy:"Photograph by Jordan Hammond (@jordhammond)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Peru/peru-2.jpg",title:"PERU",description:"<ul><li>Meet locals and watch them weave the colourful creations they are famous for</li><li>Experience the spiritual at the majestic ruins of Machu Picchu as you visualise the lives of royalty, craftsmen and servants</li><li>Gaze on wondrous architecture from the most beautiful churches in the Americas to the well-preserved ruins of ancient Inca fortresses</li></ul><center><p><b>12 Days</b><br>30 August – 10 September 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Jordan Hammond (@jordhammond)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Peru/peru-3.jpg",title:"PERU",description:"<ul><li>Meet locals and watch them weave the colourful creations they are famous for</li><li>Experience the spiritual at the majestic ruins of Machu Picchu as you visualise the lives of royalty, craftsmen and servants</li><li>Gaze on wondrous architecture from the most beautiful churches in the Americas to the well-preserved ruins of ancient Inca fortresses</li></ul><center><p><b>12 Days</b><br>30 August – 10 September 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Jordan Hammond (@jordhammond)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Peru/peru-4.jpg",title:"PERU",description:"<ul><li>Meet locals and watch them weave the colourful creations they are famous for</li><li>Experience the spiritual at the majestic ruins of Machu Picchu as you visualise the lives of royalty, craftsmen and servants</li><li>Gaze on wondrous architecture from the most beautiful churches in the Americas to the well-preserved ruins of ancient Inca fortresses</li></ul><center><p><b>12 Days</b><br>30 August – 10 September 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Jordan Hammond (@jordhammond)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Peru/peru-5.jpg",title:"PERU",description:"<ul><li>Meet locals and watch them weave the colourful creations they are famous for</li><li>Experience the spiritual at the majestic ruins of Machu Picchu as you visualise the lives of royalty, craftsmen and servants</li><li>Gaze on wondrous architecture from the most beautiful churches in the Americas to the well-preserved ruins of ancient Inca fortresses</li></ul><center><p><b>12 Days</b><br>30 August – 10 September 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Jordan Hammond (@jordhammond)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Peru/peru-6.jpg",title:"PERU",description:"<ul><li>Meet locals and watch them weave the colourful creations they are famous for</li><li>Experience the spiritual at the majestic ruins of Machu Picchu as you visualise the lives of royalty, craftsmen and servants</li><li>Gaze on wondrous architecture from the most beautiful churches in the Americas to the well-preserved ruins of ancient Inca fortresses</li></ul><center><p><b>12 Days</b><br>30 August – 10 September 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Jordan Hammond (@jordhammond)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Peru/peru-7.jpg",title:"PERU",description:"<ul><li>Meet locals and watch them weave the colourful creations they are famous for</li><li>Experience the spiritual at the majestic ruins of Machu Picchu as you visualise the lives of royalty, craftsmen and servants</li><li>Gaze on wondrous architecture from the most beautiful churches in the Americas to the well-preserved ruins of ancient Inca fortresses</li></ul><center><p><b>12 Days</b><br>30 August – 10 September 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Jordan Hammond (@jordhammond)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Peru/peru-8.jpg",title:"PERU",description:"<ul><li>Meet locals and watch them weave the colourful creations they are famous for</li><li>Experience the spiritual at the majestic ruins of Machu Picchu as you visualise the lives of royalty, craftsmen and servants</li><li>Gaze on wondrous architecture from the most beautiful churches in the Americas to the well-preserved ruins of ancient Inca fortresses</li></ul><center><p><b>12 Days</b><br>30 August – 10 September 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Jordan Hammond (@jordhammond)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Peru/peru-9.jpg",title:"PERU",description:"<ul><li>Meet locals and watch them weave the colourful creations they are famous for</li><li>Experience the spiritual at the majestic ruins of Machu Picchu as you visualise the lives of royalty, craftsmen and servants</li><li>Gaze on wondrous architecture from the most beautiful churches in the Americas to the well-preserved ruins of ancient Inca fortresses</li></ul><center><p><b>12 Days</b><br>30 August – 10 September 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Jordan Hammond (@jordhammond)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Peru/peru-10.jpg",title:"PERU",description:"<ul><li>Meet locals and watch them weave the colourful creations they are famous for</li><li>Experience the spiritual at the majestic ruins of Machu Picchu as you visualise the lives of royalty, craftsmen and servants</li><li>Gaze on wondrous architecture from the most beautiful churches in the Americas to the well-preserved ruins of ancient Inca fortresses</li></ul><center><p><b>12 Days</b><br>30 August – 10 September 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners</b></p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Jordan Hammond (@jordhammond)"}]},{image:"https://www.canon.com.au/~/media/Images/christmas/baltic",title:"RUSSIA",subtitle1:"Dream away on a private tour of fairy castle architecture, fairy tale lands and medieval magic",subtitle2:"9 - 20 June 2019",subtitle3:"2 People",brochure:"https://www.canon.com.au/~/media/Images/christmas/Russia--The-Baltics-Itinerary.pdf",litebox:[{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Baltics/Baltics-1.jpg",title:"RUSSIA and THE BALTICS",description:"<p>Focus in tighter and capture the real mystery on a tour with just 4 other people. Extravagant architecture, ancient culture, strange customs and every imaginable landscape are waiting to hold you – and your camera - in their spell.</p><ul><li>Immerse yourself in the Old Town of Vilnius in Lithuania and take in the postcard-pretty island castle at Trakai</li><li>Enjoy a romantic evening in a town nestled between emerald forests, velvet hills and a crystal river where you can walk a treetop path</li><li>Sample Birzai beer in a castle cellar and get up close and personal with the 18th Century Baroque complexity of Rundale Palace</li><li>Sample Latvia’s local delicacies in the markets of Riga</li></ul>",photoBy:"Photograph by Elaine Li (@lielaine)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Baltics/Baltics-2.jpg",title:"RUSSIA and THE BALTICS",description:"<ul><li>Stand in an old Soviet nuclear bunker before savouring the more relaxing and dreamy churches and castles of Parnu and Tallinn</li><li>Sail to St Petersburg to encounter architecture at its finest, including the superb Catherine Palace, the summer residence of Tsars</li><li>Stroll the beautiful harbours and streets of Helsinki to visit the famous Church on the Rock before departing with a million memories of fairy-tales, mysteries and picture-book landscapes<br></li></ul>   <center><p><b>11 Days </b><br>9-20 June 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners </p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Elaine Li (@lielaine)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Baltics/Baltics-3.jpg",title:"RUSSIA and THE BALTICS",description:"<ul><li>Stand in an old Soviet nuclear bunker before savouring the more relaxing and dreamy churches and castles of Parnu and Tallinn</li><li>Sail to St Petersburg to encounter architecture at its finest, including the superb Catherine Palace, the summer residence of Tsars</li><li>Stroll the beautiful harbours and streets of Helsinki to visit the famous Church on the Rock before departing with a million memories of fairy-tales, mysteries and picture-book landscapes<br></li></ul>   <center><p><b>11 Days </b><br>9-20 June 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners </p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Elaine Li (@lielaine)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Baltics/Baltics-4.jpg",title:"RUSSIA and THE BALTICS",description:"<ul><li>Stand in an old Soviet nuclear bunker before savouring the more relaxing and dreamy churches and castles of Parnu and Tallinn</li><li>Sail to St Petersburg to encounter architecture at its finest, including the superb Catherine Palace, the summer residence of Tsars</li><li>Stroll the beautiful harbours and streets of Helsinki to visit the famous Church on the Rock before departing with a million memories of fairy-tales, mysteries and picture-book landscapes<br></li></ul>   <center><p><b>11 Days </b><br>9-20 June 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners </p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Elaine Li (@lielaine)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Baltics/Baltics-5.jpg",title:"RUSSIA and THE BALTICS",description:"<ul><li>Stand in an old Soviet nuclear bunker before savouring the more relaxing and dreamy churches and castles of Parnu and Tallinn</li><li>Sail to St Petersburg to encounter architecture at its finest, including the superb Catherine Palace, the summer residence of Tsars</li><li>Stroll the beautiful harbours and streets of Helsinki to visit the famous Church on the Rock before departing with a million memories of fairy-tales, mysteries and picture-book landscapes<br></li></ul>   <center><p><b>11 Days </b><br>9-20 June 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners </p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",
photoBy:"Photograph by Elaine Li (@lielaine)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Baltics/Russia-1.jpg",title:"RUSSIA and THE BALTICS",description:"<ul><li>Stand in an old Soviet nuclear bunker before savouring the more relaxing and dreamy churches and castles of Parnu and Tallinn</li><li>Sail to St Petersburg to encounter architecture at its finest, including the superb Catherine Palace, the summer residence of Tsars</li><li>Stroll the beautiful harbours and streets of Helsinki to visit the famous Church on the Rock before departing with a million memories of fairy-tales, mysteries and picture-book landscapes<br></li></ul>   <center><p><b>11 Days </b><br>9-20 June 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners </p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Denys Black (@denys_black)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Baltics/Russia-2.jpg",title:"RUSSIA and THE BALTICS",description:"<ul><li>Stand in an old Soviet nuclear bunker before savouring the more relaxing and dreamy churches and castles of Parnu and Tallinn</li><li>Sail to St Petersburg to encounter architecture at its finest, including the superb Catherine Palace, the summer residence of Tsars</li><li>Stroll the beautiful harbours and streets of Helsinki to visit the famous Church on the Rock before departing with a million memories of fairy-tales, mysteries and picture-book landscapes<br></li></ul>   <center><p><b>11 Days </b><br>9-20 June 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners </p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Denys Black (@denys_black)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Baltics/Russia-3.jpg",title:"RUSSIA and THE BALTICS",description:"<ul><li>Stand in an old Soviet nuclear bunker before savouring the more relaxing and dreamy churches and castles of Parnu and Tallinn</li><li>Sail to St Petersburg to encounter architecture at its finest, including the superb Catherine Palace, the summer residence of Tsars</li><li>Stroll the beautiful harbours and streets of Helsinki to visit the famous Church on the Rock before departing with a million memories of fairy-tales, mysteries and picture-book landscapes<br></li></ul>   <center><p><b>11 Days </b><br>9-20 June 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners </p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Denys Black (@denys_black)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Baltics/Russia-4.jpg",title:"RUSSIA and THE BALTICS",description:"<ul><li>Stand in an old Soviet nuclear bunker before savouring the more relaxing and dreamy churches and castles of Parnu and Tallinn</li><li>Sail to St Petersburg to encounter architecture at its finest, including the superb Catherine Palace, the summer residence of Tsars</li><li>Stroll the beautiful harbours and streets of Helsinki to visit the famous Church on the Rock before departing with a million memories of fairy-tales, mysteries and picture-book landscapes<br></li></ul>   <center><p><b>11 Days </b><br>9-20 June 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners </p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Denys Black (@denys_black)"},{image:"https://www.canon.com.au/-/media/images/christmas/carousels/Baltics/Russia-5.jpg",title:"RUSSIA and THE BALTICS",description:"<ul><li>Stand in an old Soviet nuclear bunker before savouring the more relaxing and dreamy churches and castles of Parnu and Tallinn</li><li>Sail to St Petersburg to encounter architecture at its finest, including the superb Catherine Palace, the summer residence of Tsars</li><li>Stroll the beautiful harbours and streets of Helsinki to visit the famous Church on the Rock before departing with a million memories of fairy-tales, mysteries and picture-book landscapes<br></li></ul>   <center><p><b>11 Days </b><br>9-20 June 2019<br>2 People<br>Curated Tour – Total 6 people</p><p><b>Includes:</b>Economy class flights, accommodation, transportation, admission to attractions, daily tours and guides, daily breakfast, some lunches and dinners </p><p><b>PLUS $1000 SPENDING MONEY</b></p></center>",photoBy:"Photograph by Denys Black (@denys_black)"}]}],tt=[{category:"COMPACT CAMERAS",product:"IXUS 185",entries:1},{category:"COMPACT CAMERAS",product:"IXUS 190",entries:1},{category:"COMPACT CAMERAS",product:"IXUS 285",entries:1},{category:"COMPACT CAMERAS",product:"PowerShot SX60 HS",entries:2},{category:"COMPACT CAMERAS",product:"PowerShot SX70 HS",entries:2},{category:"COMPACT CAMERAS",product:"PowerShot SX430 HS",entries:2},{category:"COMPACT CAMERAS",product:"PowerShot SX540 HS",entries:2},{category:"COMPACT CAMERAS",product:"PowerShot SX620 HS",entries:2},{category:"COMPACT CAMERAS",product:"PowerShot SX730 HS",entries:2},{category:"COMPACT CAMERAS",product:"PowerShot SX740 HS",entries:2},{category:"COMPACT CAMERAS",product:"PowerShot G1X Mark III",entries:3},{category:"COMPACT CAMERAS",product:"PowerShot G3 X",entries:3},{category:"COMPACT CAMERAS",product:"PowerShot G5 X",entries:3},{category:"COMPACT CAMERAS",product:"PowerShot G7 X",entries:3},{category:"COMPACT CAMERAS",product:"PowerShot G7 X Mark II",entries:3},{category:"COMPACT CAMERAS",product:"PowerShot G9 X Mark II",entries:3},{category:"DSLR",product:"EOS 1DX Mark II (Body or Kit)",entries:5},{category:"DSLR",product:"EOS 5D Mark IV (Body or Kit)",entries:5},{category:"DSLR",product:"EOS 5DS",entries:5},{category:"DSLR",product:"EOS 5DsR",entries:5},{category:"DSLR",product:"EOS 6D Mark II (Body or Kit)",entries:5},{category:"DSLR",product:"EOS 7D Mark II (Body or Kit)",entries:3},{category:"DSLR",product:"EOS 77D (Body or Kit)",entries:3},{category:"DSLR",product:"EOS 80D (Body or Kit)",entries:3},{category:"DSLR",product:"EOS 200D (Body or Kit)",entries:3},{category:"DSLR",product:"EOS 700D (Body or Kit)",entries:3},{category:"DSLR",product:"EOS 800D (Body or Kit)",entries:3},{category:"DSLR",product:"EOS 1500D (Body or Kit)",entries:3},{category:"DSLR",product:"EOS 3000D (Body or Kit)",entries:3},{category:"MIRRORLESS",product:"EOS M5 (Body or Kit)",entries:5},{category:"MIRRORLESS",product:"EOS M6 (Body or Kit)",entries:5},{category:"MIRRORLESS",product:"EOS M50 (Body or Kit)",entries:5},{category:"MIRRORLESS",product:"EOS M100 (Body or Kit)",entries:5},{category:"EOS R SYSTEM",product:"EOS R (Body or Kit)",entries:10},{category:"EOS R SYSTEM",product:"RF 24-105mm f/4 L IS USM",entries:10},{category:"EOS R SYSTEM",product:"RF 28-70mm f/2 L USM",entries:10},{category:"EOS R SYSTEM",product:"RF 35mm f/1.8 IS STM",entries:10},{category:"EOS R SYSTEM",product:"RF 50mm f/1.2 L USM",entries:10},{category:"SPEEDLITE",product:"Speedlite 270EX II",entries:2},{category:"SPEEDLITE",product:"Speedlite 430EX III",entries:2},{category:"SPEEDLITE",product:"Speedlite 430EX III-RT",entries:2},{category:"SPEEDLITE",product:"Speedlite 470EX-AI",entries:2},{category:"SPEEDLITE",product:"Speedlite EL-100",entries:2},{category:"SPEEDLITE",product:"Speedlite 600EX II-RT",entries:2},{category:"SPEEDLITE",product:"Macro Ring Lite MR 14EX II",entries:2},{category:"SPEEDLITE",product:"Macro Twin Lite MT 26EX-RT",entries:2},{category:"VIDEO",product:"Legria HF G40",entries:2},{category:"VIDEO",product:"Legria HFR 806",entries:2},{category:"VIDEO",product:"XA30",entries:2},{category:"VIDEO",product:"XA35",entries:2},{category:"VIDEO",product:"XC10",entries:2},{category:"VIDEO",product:"XC15",entries:2},{category:"VIDEO",product:"XF105",entries:2},{category:"VIDEO",product:"XF200",entries:2},{category:"VIDEO",product:"XF205",entries:2},{category:"VIDEO",product:"XF300",entries:2},{category:"VIDEO",product:"XF400",entries:2},{category:"VIDEO",product:"XF405",entries:2},{category:"LENS (L Series)",product:"EF 11-24L EF 11-24mm f/4L USM",entries:5},{category:"LENS (L Series)",product:"EF 14mm f/2.8L II USM",entries:5},{category:"LENS (L Series)",product:"EF 16-35mm 1:2.8 L III USM",entries:5},{category:"LENS (L Series)",product:"EF 16-35mm f/4L IS USM",entries:5},{category:"LENS (L Series)",product:"EF 24-70mm f/4L IS USM",entries:5},{category:"LENS (L Series)",product:"EF 50mm f/1.2L USM",entries:5},{category:"LENS (L Series)",product:"EF 70-200mm f/4L IS USM",entries:5},{category:"LENS (L Series)",product:"EF 70-200mm f/4L IS II USM",entries:5},{category:"LENS (L Series)",product:"EF 85mm 1:1.4L IS USM",entries:5},{category:"LENS (L Series)",product:"EF 8-15mm f/4.L Fisheye USM",entries:5},{category:"LENS (L Series)",product:"EF 100mm f/2.8L Macro IS USM",entries:5},{category:"LENS (L Series)",product:"EF 180mm f/3.5L Macro USM",entries:5},{category:"LENS (L Series)",product:"EF 24-105MM F/4L IS II USM",entries:5},{category:"LENS (L Series)",product:"EF 24-70mm f/2.8 L II USM",entries:5},{category:"LENS (L Series)",product:"EF 200mm f/2.0L IS USM",entries:5},{category:"LENS (L Series)",product:"EF 70-200mm f/2.8L IS II USM",entries:5},{category:"LENS (L Series)",product:"EF 300mm f/2.8L IS II USM",entries:5},{category:"LENS (L Series)",product:"EF 300mm f/4L IS USM",entries:5},{category:"LENS (L Series)",product:"EF 400mm f/2.8L IS II USM",entries:5},{category:"LENS (L Series)",product:"EF 400mm f/5.6L USM",entries:5},{category:"LENS (L Series)",product:"EF 400mm f/4 DO IS II USM",entries:5},{category:"LENS (L Series)",product:"EF 500mm f/4L IS II USM",entries:5},{category:"LENS (L Series)",product:"EF 600mm f/4L IS II USM",entries:5},{category:"LENS (L Series)",product:"EF 800mm f/5.6L IS USM",entries:5},{category:"LENS (L Series)",product:"EF 100-400mm f4.5-5.6L IS II USM",entries:5},{category:"LENS (L Series)",product:"EF 135mm f/2L USM",entries:5},{category:"LENS (L Series)",product:"EF 200mm f/2.8L II USM",entries:5},{category:"LENS (L Series)",product:"EF 200-400mm f/4L IS USM with Ext 1.4x",entries:5},{category:"LENS (L Series)",product:"EF 70-200mm f/2.8L IS III USM",entries:5},{category:"LENS (L Series)",product:"EF 70-200mm f/4L USM",entries:5},{category:"LENS (L Series)",product:"EF 70-200mm f/2.8L USM",entries:5},{category:"LENS (L Series)",product:"EF 70-300mm f/4-5.6L IS USM",entries:5},{category:"LENS (L Series)",product:"EF 85mm f/1.2L II USM",entries:5},{category:"LENS (L Series)",product:"TS-E 135mm 1:4L Macro",entries:5},{category:"LENS (L Series)",product:"TS-E50mm 1:2.8L Macro",entries:5},{category:"LENS (L Series)",product:"TS-E90mm 1:2.8L Macro",entries:5},{category:"LENS (L Series)",product:"TS-E 17mm f/4L",entries:5},{category:"LENS (L Series)",product:"TS-E 24mm f/3.5L II",entries:5},{category:"LENS (L Series)",product:"EF 17-40mm f/4L USM",entries:5},{category:"LENS (L Series)",product:"EF 24mm f/1.4L USM",entries:5},{category:"LENS (L Series)",product:"EF 35mm f/1.4L II USM",entries:5},{category:"LENS (L Series)",product:"EF 28-300mm f/3.5-5.6L IS USM",entries:5},{category:"LENS (L Series)",product:"EF 70-200mm f/2.8L IS USM",entries:5},{category:"LENS (L Series)",product:"EF 400mm f/2.8L IS III USM",entries:5},{category:"LENS (L Series)",product:"EF 600mm f/4L IS III USM",entries:5},{category:"LENS (Excluding L Series)",product:"EF-M 11-22mm f/4-5.6 IS STM",entries:2},{category:"LENS (Excluding L Series)",product:"EF-M 15-45mm IS ST f/3.5-6.3 IS STM",entries:2},{category:"LENS (Excluding L Series)",product:"EF-M 18-150mm 1:3.5-6.3 IS STM",entries:2},{category:"LENS (Excluding L Series)",product:"EF-M 22mm f/2 STM",entries:2},{category:"LENS (Excluding L Series)",product:"EF-M 28mm f/3.5 Macro",entries:2},{category:"LENS (Excluding L Series)",product:"EF-M 55-200mm f/4.5-6.3 IS STM",entries:2},{category:"LENS (Excluding L Series)",product:"EF-M 32mm f/1.4 STM",entries:2},{category:"LENS (Excluding L Series)",product:"EF 35mm f/2 IS USM",entries:2},{category:"LENS (Excluding L Series)",product:"EF-S 55-250mm f/4-5.6 IS STM",entries:2},{category:"LENS (Excluding L Series)",product:"EF 1.4x Mark III",entries:2},{category:"LENS (Excluding L Series)",product:"EF 2x Mark III",entries:2},{category:"LENS (Excluding L Series)",product:"EF 100mm f/2.8 Macro USM",entries:2},{category:"LENS (Excluding L Series)",product:"EF-S 35mm f/2.8 IS STM Macro",entries:2},{category:"LENS (Excluding L Series)",product:"EF-S 60mm f/2.8 Macro USM",entries:2},{category:"LENS (Excluding L Series)",product:"MPE6528 f/2.8 1-5x Macro Photo",entries:2},{category:"LENS (Excluding L Series)",product:"EF 24-105mm f/3.5-5.6 IS STM",entries:2},{category:"LENS (Excluding L Series)",product:"EF 40mm f/2.8 STM",entries:2},{category:"LENS (Excluding L Series)",product:"EF 50mm f/1.4 USM",entries:2},{category:"LENS (Excluding L Series)",product:"EF 50mm f/1.8 STM",entries:2},{category:"LENS (Excluding L Series)",product:"EF-S 15-85mm f/3.5-5.6 IS USM",entries:2},{category:"LENS (Excluding L Series)",product:"EF-S 17-55mm f/2.8 IS USM",entries:2},{category:"LENS (Excluding L Series)",product:"EF-S 18-135mm 1:3.5-5.6 IS USM",entries:2},{category:"LENS (Excluding L Series)",product:"EF-S 18-55mm f/3.5-5.6 IS STM",entries:2},{category:"LENS (Excluding L Series)",product:"EF-S 18-55mm f/4-5.6 IS ST",entries:2},{category:"LENS (Excluding L Series)",product:"EF-S 24mm f/2.8 STM",entries:2},{category:"LENS (Excluding L Series)",product:"EF 100mm f/2 USM",entries:2},{category:"LENS (Excluding L Series)",product:"EF 70-300mm 1:4-5.6 IS II USM",entries:2},{category:"LENS (Excluding L Series)",product:"EF 75-300mm F4-5.6",entries:2},{category:"LENS (Excluding L Series)",product:"EF 85mm f/1.8 USM",entries:2},{category:"LENS (Excluding L Series)",product:"EF 20mm f/2.8 USM",entries:2},{category:"LENS (Excluding L Series)",product:"EF 24mm f/2.8 IS USM",entries:2},{category:"LENS (Excluding L Series)",product:"EF 28mm f/1.8 USM",entries:2},{category:"LENS (Excluding L Series)",product:"EF 28mm f/2.8 IS USM",entries:2},{category:"LENS (Excluding L Series)",product:"EF-S10-18mm f/4.5-5.6 IS STM",entries:2},{category:"LENS (Excluding L Series)",product:"EF-S10-22mm f/3.5-4.5 USM",entries:2},{category:"LENS (Excluding L Series)",product:"Advanced Portrait Pack",entries:2},{category:"LENS (Excluding L Series)",product:"Portrait Starter Pack",entries:2},{category:"PRINTERS",product:"PRO 1000",entries:5},{category:"PRINTERS",product:"PRO 100S",entries:5},{category:"PRINTERS",product:"PRO 10S",entries:5},{category:"PRINTERS",product:"PIXMA Endurance G4600",entries:2},{category:"PRINTERS",product:"PIXMA Endurance G4610",entries:2},{category:"PRINTERS",product:"PIXMA Endurance G3600",entries:2},{category:"PRINTERS",product:"PIXMA Endurance G3610",entries:2},{category:"PRINTERS",product:"PIXMA Endurance G2600",entries:2},{category:"PRINTERS",product:"PIXMA Home TS9160",entries:1},{category:"PRINTERS",product:"PIXMA Home TS9060",entries:1},{category:"PRINTERS",product:"PIXMA Home TS8160",entries:1},{category:"PRINTERS",product:"PIXMA Home TS8060",entries:1},{category:"PRINTERS",product:"PIXMA Home TS8260",entries:1},{category:"PRINTERS",product:"PIXMA Home TS6160",entries:1},{category:"PRINTERS",product:"PIXMA Home TS6060",entries:1},{category:"PRINTERS",product:"PIXMA Home TS6260",entries:1},{category:"PRINTERS",product:"PIXMA Home TS5160",entries:1},{category:"PRINTERS",product:"PIXMA Home TS5060",entries:1},{category:"PRINTERS",product:"PIXMA Home TS3160",entries:1},{category:"PRINTERS",product:"PIXMA Home TS9560 (A3)",entries:1},{category:"PRINTERS",product:"PIXMA Home MG7766",entries:1},{category:"PRINTERS",product:"PIXMA Home MG7765",entries:1},{category:"PRINTERS",product:"PIXMA Home MG7760",entries:1},{category:"PRINTERS",product:"PIXMA Home MG7560",entries:1},{category:"PRINTERS",product:"PIXMA Home MG6865",entries:1},{category:"PRINTERS",product:"PIXMA Home MG6860",entries:1},{category:"PRINTERS",product:"PIXMA Home MG5765",entries:1},{category:"PRINTERS",product:"PIXMA Home MG5760",entries:1},{category:"PRINTERS",product:"PIXMA Home MG3660",entries:1},{category:"PRINTERS",product:"PIXMA Home MG3560",entries:1},{category:"PRINTERS",product:"PIXMA Home MG3060",entries:1},{category:"PRINTERS",product:"PIXMA Home MG2965",entries:1},{category:"PRINTERS",product:"PIXMA Home MG2960",entries:1},{category:"PRINTERS",product:"PIXMA Home MG2560",entries:1},{category:"PRINTERS",product:"PIXMA Home MG2460",entries:1},{category:"PRINTERS",product:"PIXMA Home Office MX926",entries:1},{category:"PRINTERS",product:"PIXMA Home Office MX726",entries:1},{category:"PRINTERS",product:"PIXMA Home Office MX536",entries:1},{category:"PRINTERS",product:"PIXMA Home Office MX496",entries:1},{category:"PRINTERS",product:"PIXMA Home Office TR8560",entries:1},{category:"PRINTERS",product:"PIXMA Home Office TR7560",entries:1},{category:"PRINTERS",product:"PIXMA Home Office TR4560",entries:1},{category:"PRINTERS",product:"MAXIFY Office MB5460",entries:1},{category:"PRINTERS",product:"MAXIFY Office MB5360",entries:1},{category:"PRINTERS",product:"MAXIFY Office MB5160",entries:1},{category:"PRINTERS",product:"MAXIFY Office MB5060",entries:1},{category:"PRINTERS",product:"MAXIFY Office MB 2760",entries:1},{category:"PRINTERS",product:"MAXIFY Office MB 2360",entries:1},{category:"PRINTERS",product:"MAXIFY Office MB 2160",entries:1},{category:"PRINTERS",product:"PIXMA MP230",entries:1},{category:"PRINTERS",product:"PIXMA iP8760",entries:1},{category:"PRINTERS",product:"PIXMA iP7260",entries:1},{category:"PRINTERS",product:"PIXMA iX6860",entries:1},{category:"PORTABLE PRINTERS",product:"Selphy CP910",entries:1},{category:"PORTABLE PRINTERS",product:"Selphy CP1200",entries:1},{category:"PORTABLE PRINTERS",product:"Selphy CP1300",entries:1},{category:"PORTABLE PRINTERS",product:"Mini Photo Printer",entries:1}];$(".cb33 .tile--118").click(function(e){"expanded-inner"!=e.target.parentNode.className&&"expanded-inner"!=e.target.className&&(e.preventDefault(),$(this).toggleClass("active"),$(this).siblings().removeClass("active"))}),$(".cp12 ul.tabs li").click(function(){var e=$(this).attr("data-tab");$(".cp12 ul.tabs li").removeClass("active"),$(".cp12 ul").removeClass("active"),$(this).addClass("active"),$("#"+e).addClass("active")}),$("#nv-19-quicklinks .nv19--1-nav-container>div").click(function(){var e=$(this).attr("data-tab");$("#nv-19-quicklinks .nv19--1-nav-container>div").removeClass("nav-active"),$("#nv-19-quicklinks .nv19--1-link-container ul").removeClass("active"),$(this).addClass("nav-active"),$("#"+e).addClass("active")}),$(".cb03, .cf09").each(function(e){e%2===1&&$(this).find(".content > div:last-child").addClass("order--1")}),$(".tiled--2x-c1 ul").each(function(e,t){$this=$(this),$a=e%4+1,$this.find("li").each(function(e,t){$(this).css("order",2*(e+1))}),$this.find("li:first-child").addClass("order--"+(2*$a+1))});var at=!1;window.location.href.indexOf("co.nz")>0&&(at=!0,$("footer .row3 a.active").removeClass("active"),$("footer .row3 a[href*='co.nz']").addClass("active")),T(),$(window).resize(function(){T()}),$(".cb01a .info span").on("click",function(e){$this=$(".cb01a .over-sideinfo"),0==parseFloat($(".cb01a .over-sideinfo").css("opacity"))?TweenMax.to($this,.5,{css:{opacity:1},ease:Power4.easeOut}):TweenMax.to($this,.5,{css:{opacity:0},ease:Power4.easeOut})});var it=function(){function e(){a.find(".mobile .but-container, .mobile .close").on("click",function(e){e.stopPropagation(),$(this).parent().toggleClass("m-open"),t()}),$(window).on("scroll",$.throttle(280,t))}function t(){a.find(".mobile .menu").hasClass("m-open")&&a.hasClass("sticky--fixed")?$("html").addClass("f-open"):$("html").removeClass("f-open")}var a=$(".nv15");return{_init:function(){e()}}};if($(".nv15").length>0){var ot=it();ot._init()}var nt="pkdl",st=RegExp("[?&]"+nt+"=([^&]*)").exec(window.location.search);if(st&&"true"==st[1]&&$(".fl02").addClass("active"),$(".cb15a #serial-search-box").on("keypress",function(e){var t=e.keyCode;$(this).parent().addClass("is-searching"),13==t&&($(".cb15a").find("#service .section").removeClass("active"),$(this).parent().removeClass("is-searching"),"1234"!=$(this).val()?$(".cb15a").find("#service #incorrect-serial").addClass("active"):$(".cb15a").find("#service #serial-result-found").addClass("active"))}),$(".cb15a .clear-search").on("click",function(e){e.preventDefault(),$(this).parent().removeClass("is-searching"),$(".cb15a #serial-search-box").val("")}),$(".cb15a #serial-search-box").on("keyup",function(e){var t=e.keyCode;8!=t&&46!=t||""==$(this).val()&&$(this).parent().removeClass("is-searching")}),$(".cb15a .product-search-box").on("keypress",function(e){var t=e.keyCode;13==t&&("product1"!=$(this).val()?$(".cb15a").find("#service .incorrect-product-text").addClass("active"):($(".cb15a").find("#service .section").removeClass("active"),$(".cb15a").find("#service #correct-product").addClass("active")))}),$(".cb15a .product-search-container a").on("click",function(e){e.preventDefault(),"product1"!=$(this).closest(".product-search-container").find(".product-search-box").val()?$(".cb15a").find("#service .incorrect-product-text").addClass("active"):($(".cb15a").find("#service .section").removeClass("active"),$(".cb15a").find("#service #correct-product").addClass("active"))}),$(".cb15a .section-trigger").on("click",function(e){e.preventDefault();var t=$(this).data("section-id");$(".cb15a").find("#service .section,#service .sub-section").removeClass("active"),$(".cb15a").find("#"+t).addClass("active")}),$(".cb15a .sub-section-trigger").on("click",function(e){e.preventDefault();var t=$(this).data("section-id");$(".cb15a").find("#service .sub-section").removeClass("active"),$(".cb15a").find("#"+t).addClass("active")}),$(".cb15a .tab").on("click",function(e){e.preventDefault();var t=$(this).data("tab-id");$(".cb15a").find("#service .tab-content,#service .tab").removeClass("active"),$(".cb15a").find("#"+t).addClass("active"),$(this).addClass("active")}),$(".cb15a #error-dropdown").on("change",function(){$(".cb15a").find("#error .sub-section").removeClass("active"),$("#"+$(this).val()).addClass("active")}),$(".nv09 .close").on("click",function(e){$(".nv09").toggleClass("show")}),$('.file input[type="file"]').change(function(){var e=$(this).val();$(this).next().text(e.split("\\").pop())}),$(".dpicker").datepicker({showOn:"both",buttonImage:"/images/svg/icon-datepicker.svg",buttonImageOnly:!0,buttonText:"Select date",dateFormat:"dd/mm/yy",maxDate:"0"}),navigator.appVersion.indexOf("MSIE 10")!==-1&&$(".cb02, .cb02a").length>0){var rt=$(".carousel-wrap .carousel-image-container").width();$(".carousel-wrap .carousel-images > div").css("maxWidth",rt)}var lt=function(){function e(){a("https://cdnjs.cloudflare.com/ajax/libs/gsap/1.19.0/plugins/TextPlugin.min.js",t)}function t(){a("https://unpkg.com/isotope-layout@3/dist/isotope.pkgd.min.js",o)}function a(e,t){var a=document.createElement("script");a.setAttribute("src",e),a.onload=t,document.body.appendChild(a)}function i(){function e(e){var t="";return t=e>="A"&&e<="E"?"A-E":e>="F"&&e<="J"?"F-J":e>="K"&&e<="O"?"K-O":e>="P"&&e<="T"?"P-T":"U-Z"}l.find("ul").each(function(){if($(this).attr("data-letter")){var t=String($(this).attr("data-letter"));d[t]=[],$(this).find("li").each(function(a,i){if($(this).attr("data-video")){var o={video:$(this).attr("data-video"),image:$(this).attr("data-image"),letter:t,cName:e(t)};u.push(o)}var n={text:$(this).find("a").text(),link:$(this).find("a").attr("href")};d[t].push(n)})}});for(var t in d)if(void 0!=d[t][0]){var a=e(t),i='<div class="letter '+a+'" data-letter="'+t+'"><div class="aratio--1-1"><div class="label">'+t+'</div><div class="text">'+d[t][0].text+"</div></div></div>";l.find(".container .content").append(i)}i='<div class="letter blank"><div class="aratio--1-1"></div></div>',l.find(".container .content > div:nth-child(1)").after(i);var o=[5,9,11,12,17,21,23,27,28,33],r=0;for(var t in u)if(i='<div class="letter blank video '+u[t].cName+'"><div class="aratio--1-1"><div class="img-content"> <img src="'+u[t].image+'" alt=""><div class="play video"><span class="icon-svg-playbutton"></span><iframe width="800" height="600" src="'+u[t].video+'" frameborder="0" allowfullscreen></iframe></div></div></div></div>',l.find(".container .content div:nth-child("+o[r]+")").after(i),r++,r>9)break;c(".cf12"),i='<div class="meta" style="top:-999px"><div class="cap">M</div><div class="line">|</div> <div class="links"><ul class=""><li>link1</li></ul></div><button><span class="icomoon-Close"></span></button></div>',l.find(".container .content").append(i);for(var p=[5,16,23,26,33],h=0,m=p.length;h<m;h++)l.find(".container .content div:nth-child("+p[h]+")").addClass("letter--width2");$(".cf12 .container .content").on("mouseover",".letter:not(.blank)",function(){n=new TimelineMax({repeat:-1,yoyo:!1,repeatDelay:.2});var e=$(this).find(".text");for(h=1,m=d[$(this).attr("data-letter")].length;h<m;h++)n.to(e,0,{text:{value:d[$(this).attr("data-letter")][h].text,padSpace:!1,ease:Linear.easeIn},delay:.2})}),$(".cf12 .container .content").on("mouseout",".letter",function(){if(n)try{n.kill()}catch(e){}}),$(".cf12 .container .content .meta button").on("click",function(){$(".cf12 .container .content .meta").removeClass("show"),$(".cf12 .container .content .active").removeClass("active"),TweenMax.to($(".cf12 .container .content .meta"),.35,{css:{top:"-9999"},delay:.35}),$(".cf12 .container .content").attr("data-org")&&TweenMax.to($(".cf12 .container .content"),.35,{css:{height:$(".cf12 .container .content").attr("data-org")},delay:.35}),$(".cf12 .container .content").removeAttr("data-org")}),$(".cf12 .container .content").on("click",".letter",function(){if($(this).hasClass("blank"))return null;if($(this).hasClass("active"));else{var e=$(this).position().top+$(this).height();$(this).parent().find(".meta").removeClass("show"),$(this).parent().find(".meta").css("top",e).addClass("show");var t=$(this).parent().offset().top;t=$(window).scrollTop()+$(this).parent().find(".meta")[0].getBoundingClientRect().top,t-="relative"===$(".gl01").css("position")?170:100,$("html,body").animate({scrollTop:t},750),e>=$(this).parent().height()&&($(this).parent().attr("data-org",$(this).parent().height()),TweenMax.fromTo($(this).parent(),.15,{css:{height:$(this).parent().height()}},{css:{height:$(this).parent().height()+$(this).parent().find(".meta").height()}}),$(this).parent().css("height",$(this).parent().height()+$(this).parent().find(".meta").height())),$(this).parent().find(".active").removeClass("active"),$(this).addClass("active");var a=$(this).attr("data-letter");if($(this).parent().find(".meta .cap").text(a),$(this).parent().find(".meta .links ul").empty(),d[a].length<=6)var i="ucols--1";else i="ucols--3";for(h=0,m=d[a].length;h<m;h++)$(this).parent().find(".meta .links ul").append('<li><a href="'+d[a][h].link+'">'+d[a][h].text+"</a></li>");$(this).parent().find(".meta .links ul").removeClass("ucols--1").removeClass("ucols--3"),$(this).parent().find(".meta .links ul").addClass(i)}}),$(".cf12 .container ul.filter").on("click","li",function(){switch($(this).parent().find(".active").removeClass("active"),$(this).addClass("active"),$(this).index()){case 0:s.isotope({filter:"*"});break;case 1:s.isotope({filter:".A-E"});break;case 2:s.isotope({filter:".F-J"});break;case 3:s.isotope({filter:".K-O"});break;case 4:s.isotope({filter:".P-T"});break;case 5:s.isotope({filter:".U-Z"})}})}function o(){i(),s=$(".cf12 .container .content").isotope({itemSelector:".letter",masonry:{}}),r||$(".cf12").addClass("hover")}var n,s,r=!!/Android|webOS|iPhone|iPad|BlackBerry|Windows Phone|Opera Mini|IEMobile|Mobile/i.test(navigator.userAgent),l=$(".cf12"),d=[],u=[];return{_init:function(){e()}}};if($(".cf12").length>0){lt()._init()}var ct=function(){function e(){t("https://unpkg.com/isotope-layout@3/dist/isotope.pkgd.min.js",i)}function t(e,t){var a=document.createElement("script");a.setAttribute("src",e),a.onload=t,document.body.appendChild(a)}function a(){n.find("li").each(function(){var e={video:$(this).attr("data-video"),image:$(this).attr("data-image"),name:$(this).attr("data-author-name"),surname:$(this).attr("data-author-surname"),date:$(this).attr("data-date"),color:$(this).attr("data-color"),likes:$(this).attr("data-fb"),desc:$(this).attr("data-desc"),title:$(this).attr("data-title"),article:$(this).attr("data-article")};s.push(e)});var e='<div class="grid-sizer"></div>';for(var t in s){var a;a=""!==s[t].video?'<div class="brick video"><div class="aratio--1-1"><div class="img-content"><div class="gallery-image" style="background-image: url('+s[t].image+');"></div><span class="icon-svg-playbutton"></span></div><div class="positioned-together"><div class="author-name">'+s[t].name+'</div><div class="date">'+s[t].date+'</div></div><div class="fb-likes"><div class="fb-like" data-href="'+s[t].likes+'" data-layout="button_count" data-action="like" data-size="small" data-show-faces="true" data-share="false"></div></div></div></div>':""!==s[t].image?'<div class="brick image"><div class="aratio--1-1"><div class="img-content"><div class="gallery-image" style="background-image: url('+s[t].image+');"></div></div><div class="positioned-together"><div class="author-name">'+s[t].name+'</div><div class="date">'+s[t].date+'</div></div><div class="fb-likes"><div class="fb-like" data-href="'+s[t].likes+'" data-layout="button_count" data-action="like" data-size="small" data-show-faces="true" data-share="false"></div></div></div></div>':'<div class="brick article"><div class="aratio--1-1"><div class="img-content"><div class="gallery-image '+s[t].color+'"></div></div><div class="short-desc">'+s[t].desc+'</div><div class="positioned-together"><div class="author-name">'+s[t].name+'</div><div class="date">'+s[t].date+'</div></div><div class="fb-likes"><div class="fb-like" data-href="'+s[t].likes+'" data-layout="button_count" data-action="like" data-size="small" data-show-faces="true" data-share="false"></div></div></div></div>',n.find(".container .content").append(a)}n.find(".container .content").prepend(e);for(var i=[2,13],o=0,r=i.length;o<r;o++)n.find(".brick:nth-child("+i[o]+")").addClass("two--width");$(".brick").each(function(e){$(this).on("click",function(){M(s[e].video,s[e].image,s[e].name,s[e].surname,s[e].date,s[e].color,s[e].likes,s[e].title,s[e].article)})})}function i(){a(),$(".cf14 .container .content").isotope({itemSelector:".brick",percentPosition:!0,masonry:{columnWidth:".grid-sizer"}}),o||$(".cf14").addClass("hover")}var o=/Android|webOS|iPhone|iPad|BlackBerry|Windows Phone|Opera Mini|IEMobile|Mobile/i.test(navigator.userAgent),n=$(".cf14"),s=[];return{_init:function(){e()}}};if($(".cf14").length>0&&ct()._init(),$(".cp20 .show-hide").on("click",function(){$(this).toggleClass("active")}),$(".tile--162").length>0){L()._init()}if($(".cf05v2").length>0){A()._init($(".cf05v2"))}if($(".cp23").length>0){var dt=["warning","caution","attention","important","note","reference"];$(".cp23 .main-text section").each(function(e,t){var a=$(this);a.find("h3").each(function(e,t){var a=$(this),i=a.next("div");if(1===i.length)for(var o=0;o<dt.length;o++)if(i.attr("class").indexOf(dt[o])>=0){a.text(dt[o].toUpperCase()),(dt[o].indexOf("warning")>=0||dt[o].indexOf("caution")>=0)&&i.attr("class").indexOf("_CS")>0&&a.addClass("icon--"+dt[o]);break}})})}if($(".tile--106").length>0){_()._init()}if($(".cla-s").length>0){D()._init()}if($(".sub--forms").length>0&&$(".sub--forms .jquery-mask").length>0){
R()._init()}if($(".how-to-video").length>1){j()._init()}if($(".how-to-video-v1").length>0){O()._init()}if($(".mcb21").length>0&&h().model){var ut=B();ut._deeplink(h().model,h().device||"mfd")}if($(".mcb21").length>0&&h().model){var ut=B();ut._deeplink(h().model,h().device||"mfd")}if($(".mcb20").length>0){var pt=G();pt._init()}$(".mc2--dash__nav").length>0&&F()._init(),$(".mcb2--dash__devices").length>0&&J()._init(),$(".forms2--elements__input-file").length>0&&Y()._init(),$(".leap--stackla__filter").length>0&&H()._init(),$(".howto--videos__journey:not(.camera-assist)").length>0&&W()._init(),$('[class*="howto--videos__chatbot"]').length>0&&W()._chatbotinit(),$(".howto--videos__journey:not(.camera-assist)").length>0&&(W()._summaryinit(),$(".howto--videos__summary .frms2--elements__info").on("click",function(){$(this).parent().toggleClass("active")})),$(".howto--videos__journey.camera-assist").length>0&&z()._init(),$('[class*="online--prop__product"]').length>0&&X()._init(),V(),$(".canonedge--header").length>0&&K()._init(),$(".prod__relacc").length>0&&Z(),$(".prod__360hot").length>0&&ee(),$(".img__gallery").length>0&&te(),$('div[id*="BVRR"]').length>0&&g(),$(".prod__specs").length>0&&ae(),$(".navigation__category-page").length>0&&ie(),$(".link__cta").length>0&&oe(),$(".ecrm__trigger-form").length>0&&ne();var ht="",mt="",ft="",gt=function(e){return function(t,a){t=t.toLowerCase();var i=e.filter(function(e){return e.toLowerCase().indexOf(t)>=0});a(i)}},bt=0;if($(document).on("click",".product-add-button",function(){we($("#product-control"))}),$(document).on("click",".product-remove-button",function(){"product-control"!==$(this).closest(".product-control").attr("id")&&($(this).closest(".product-control").remove(),pe($(this).closest(".product-control").attr("id")),$(".camp__xmas18-form .destination-label").each(function(e,t){le(0);$(this).html('<span class="count-0">0</span>')}))}),$(document).on("click",".save-button",function(){console.log($(this)),console.log($(this).closest(".product-control").attr("id")),be($(this).closest(".product-control").attr("id"))}),$("#submit-entry").on("click",function(){fe()}),$("#terms").on("click",function(){ve()}),$("#add-canada").on("click",function(){var e=$("#canada-count").text(),t=re(Number(e));$("#canada-count").html('<span class="count-'+t+'">'+t+"</span>")}),$("#add-egypt").on("click",function(){var e=$("#egypt-count").text(),t=re(Number(e));$("#egypt-count").html('<span class="count-'+t+'">'+t+"</span>")}),$("#add-iceland").on("click",function(){var e=$("#iceland-count").text(),t=re(Number(e));$("#iceland-count").html('<span class="count-'+t+'">'+t+"</span>")}),$("#add-india").on("click",function(){var e=$("#india-count").text(),t=re(Number(e));$("#india-count").html('<span class="count-'+t+'">'+t+"</span>")}),$("#add-japan").on("click",function(){var e=$("#japan-count").text(),t=re(Number(e));$("#japan-count").html('<span class="count-'+t+'">'+t+"</span>")}),$("#add-lapland").on("click",function(){var e=$("#lapland-count").text(),t=re(Number(e));$("#lapland-count").html('<span class="count-'+t+'">'+t+"</span>")}),$("#add-madagascar").on("click",function(){var e=$("#madagascar-count").text(),t=re(Number(e));$("#madagascar-count").html('<span class="count-'+t+'">'+t+"</span>")}),$("#add-morocco").on("click",function(){var e=$("#morocco-count").text(),t=re(Number(e));$("#morocco-count").html('<span class="count-'+t+'">'+t+"</span>")}),$("#add-peru").on("click",function(){var e=$("#peru-count").text(),t=re(Number(e));$("#peru-count").html('<span class="count-'+t+'">'+t+"</span>")}),$("#add-baltic").on("click",function(){var e=$("#baltic-count").text(),t=re(Number(e));$("#baltic-count").html('<span class="count-'+t+'">'+t+"</span>")}),$("#remove-canada").on("click",function(){var e=$("#canada-count").text(),t=le(Number(e));$("#canada-count").html('<span class="count-'+t+'">'+t+"</span>")}),$("#remove-egypt").on("click",function(){var e=$("#egypt-count").text(),t=le(Number(e));$("#egypt-count").html('<span class="count-'+t+'">'+t+"</span>")}),$("#remove-iceland").on("click",function(){var e=$("#iceland-count").text(),t=le(Number(e));$("#iceland-count").html('<span class="count-'+t+'">'+t+"</span>")}),$("#remove-india").on("click",function(){var e=$("#india-count").text(),t=le(Number(e));$("#india-count").html('<span class="count-'+t+'">'+t+"</span>")}),$("#remove-japan").on("click",function(){var e=$("#japan-count").text(),t=le(Number(e));$("#japan-count").html('<span class="count-'+t+'">'+t+"</span>")}),$("#remove-lapland").on("click",function(){var e=$("#lapland-count").text(),t=le(Number(e));$("#lapland-count").html('<span class="count-'+t+'">'+t+"</span>")}),$("#remove-madagascar").on("click",function(){var e=$("#madagascar-count").text(),t=le(Number(e));$("#madagascar-count").html('<span class="count-'+t+'">'+t+"</span>")}),$("#remove-morocco").on("click",function(){var e=$("#morocco-count").text(),t=le(Number(e));$("#morocco-count").html('<span class="count-'+t+'">'+t+"</span>")}),$("#remove-peru").on("click",function(){var e=$("#peru-count").text(),t=le(Number(e));$("#peru-count").html('<span class="count-'+t+'">'+t+"</span>")}),$("#remove-baltic").on("click",function(){var e=$("#baltic-count").text(),t=le(Number(e));$("#baltic-count").html('<span class="count-'+t+'">'+t+"</span>")}),$("#receipt").on("change",function(){this.value?(ft=this.files[0].name,he(this),$("#receipt").attr("placeholder",this.value)):(ht="",mt="")}),$("#retailerName").on("change",function(){"Other*"==this.value?($("#retailerOther").attr("hidden",!1),$("#retailerOtherLabel").css("display","block")):($("#retailerOther").attr("hidden",!0),$("#retailerOtherLabel").css("display","none"))}),$("input[type=radio][name=ReceiptOption]").change(function(){"Upload receipt"==this.value?($(".receipt-mail-section").hide(),$(".receipt-upload-section").show()):"Mail receipt"==this.value&&($(".receipt-upload-section").hide(),$(".receipt-mail-section").show())}),$(".fm01").length>0)var Me=Me()._init();if($(".mc-selection .selector > div").on("click",function(){$(".mc-selection .selector > div").toggleClass("active"),$(".mc02").removeClass("open"),0==$(this).index()?$(".mc02.mycanon").addClass("open"):$(".mc02.myaccount").addClass("open");var e=0;TweenMax.killAll(),$(".mc02.open li").each(function(t,a){e+=.04,TweenMax.fromTo($(this),.25,{css:{opacity:0}},{css:{opacity:1},delay:e})})}),$(".mc08a").length>0){xe()._init()}_e()});;
(function ($J, window, document) {
    $J(function () {
        var supportCategories = {};
        var currentindex = 0;
        var isLastPage = true;
        var totalCount = 0;
        var childrenPageIndex = 0;
        var selectedOption = '';
        var supportItemId = '';
        var placeSelected = '';
        var captchaWidgetId = "";
        var selectedFilter = '';
        var selectedFilter1 = '';
        var defaultFunctions = {
            init: function () {
                canonHelper.initImageLazyLoad();
                this.initMapBlock();
                this.canonsInlineJS();
                this.loadMoreFeed();
                this.initiateStickyNavigation();
                this.initiateNoneClickableLinks();
                this.initPartnerFinder();
                this.toggleRetailerRatings();
                this.initiateDropDownWithDynamicCTA();
                this.contentFeedEventsLoadMoreCall();
                this.requestPdfReports();
                this.AddFavouriteContent();
                this.DeleteFavouriteContent();
                this.wishListEvents();
                this.highlightCarousel();
                this.initScrollToNextElement();

                this.PressKitDownload();
                this.contentFeedLoadMore();

                this.theFarmRemoveEmptyList();

                this.initProductFeedFilter();
                this.initProductFeedLoadMore();
                this.forms();
                this.initLoadNZFormProductData();
                this.initLoadAUFormProductData();

                this.initAskToLoginBeforeBookEvent();
                this.initDisabledAnchor();
                this.inputtextBoxNumberValidation();
                this.HeaderStoreLinks();
                this.initProductTypeAhead();

                this.loginMessageDisplay();
                this.glossaryLinkListLoadMore();
                this.initSdsFilter();
                this.initSdsLoadMore();

                this.initEloquaForm();
                this.initFormSubmission();
                this.initImpersonation();

                this.initCarousel();

                this.initClaBookingAccordion();
                this.initLightAwardsSubmission();
                this.initOnFormSubmissionErrorMessage();
                this.bynderGallery();
                this.initStackla();
                this.initEdgesearchboxEnter();
                this.edgeSearchLoadMore();
                this.printAssistFirsttimeSetup();
                this.cb51LoadData();
                this.PartnerfinderGoogleMapInital();
                this.SDKDownloadCheckIpAdress();
                this.validateEdgeContactForm();
                // this.SDKAdressGoogleMapInital();
                this.initHatchButtonProductList();
                this.initDxComponents();
                /// Product Image gallery
                this.initProductImageGalleryButton();
                this.initPluginFocus();
                this.initRetailerRatings();
                this.initIsAlsoAvailable();
                // this.initProductFeedTilesFilter();
                this.initiateProductTileFilter();
                this.initProductFeedTilesLoadMore();
                this.initCompatibilityTable();
                this.initiateProductTile();
                this.initiateCompareBucket();
                this.initComparePage();
                this.initProductCompatibilityRefiner2();
                this.InitCB82ProductVariants();
                this.initiateNv05();
                this.InitCB56KeySpecifications();
                this.InitCB63SubCategoryNavigation();
                this.InitCB72SubCategoryFeatures();
                this.InitCB79SquareFeed();
                this.InitCB84SolutionFinder();
                this.InitCB83ArticleFinder();
                this.InitCB87RegionSwitch();
            },
            InitCB87RegionSwitch: function () {
                const cb87 = $('.cb87-region-switch').first();
                if ($(cb87).length !== 1) {
                    return;
                }

                var modalConfig = {
                    "target": "#cb87-region-switch",
                    "immediate": true,
                    "fitViewport": true,
                    "modal": ".stayHere"
                }

                if (localStorage.getItem(modalConfig.target) === "true") {
                    //do nothing.
                    return;
                }

                const userCountry = geoplugin_countryName();
                if (!["Australia", "New Zealand"].includes(userCountry)) {
                    //user not in AU or NZ
                    localStorage.setItem(modalConfig.target, true)
                    return;
                }

                const currentSite = $(cb87).attr('data-site')

                if (userCountry !== currentSite) {
                    //show modal to switch regions

                    $(cb87).find(".userLocation").text(userCountry)
                    $(cb87).find(".userLocationShort").text(userCountry === "Australia" ? "AU" : "NZ")
                    $(cb87).find(".currentLocationShort").text(currentSite === "Australia" ? "AU" : "NZ")

                    $(".cb87-modal-location").modal(modalConfig);
                }
                else {
                    //user is browsing own region
                    localStorage.setItem(modalConfig.target, true)
                }

                //user wants to stay here
                $(cb87).find(".stayHere").on("click", function () {
                    //configure local storage so we no longer prompt again
                    localStorage.setItem(modalConfig.target, true)
                    $(".cb87-modal-location").modal("hide")
                    return;
                })

                //user wants to switch
                $(cb87).find(".switchSite").on("click", function () {
                    //configure local storage to prompt again if they return to this region
                    localStorage.setItem(modalConfig.target, false)

                    const otherRegionUrl = $(cb87).attr('data-alternate-url')
                    const queryString = window.location.search;
                    const newlocation = otherRegionUrl + queryString;

                    //navigate to the other region
                    window.location = newlocation
                })
            },
            InitCB83ArticleFinder: function () {
                //DROPDOWN RELATED
                const CONTAINER_SELECTOR = '.cb83-filters';
                const DROPDOWN_TRIGGER_CLASS = 'cb83-filter-title';
                const DROPDOWN_TRIGGER_SELECTOR = `.${DROPDOWN_TRIGGER_CLASS}`;
                const OPEN_CLASS = 'open-dropdown';
                const OPEN_SELECTOR = `.${OPEN_CLASS}`;
                const CB83_DROPDOWN_CLASS = 'cb83-dropdown';
                const CB83_DROPDOWN_SELECTOR = `.${CB83_DROPDOWN_CLASS}`;
                const NO_RESULTS_CLASS = 'no-results';
                const CLOSE_BUTTON_SELECTOR = '.cb83-close-dropdown';
                const DROPDOWN_SELECTOR = '.cb83-dropdown-box';
                const FEED_CTA_SELECTOR = '.cb83-feed-cta';
                $(CB83_DROPDOWN_SELECTOR).hide();
                //FEED RELATED
                const CB83_FEED_CONTAINER = '.cb83-article-finder-result-container'
                const CB83_PARENT = '.cb83-tiles-container'
                const LOAD_MORE_BUTTON = '.cb83-more'
                const RESULTS_CONTAINER = '.results'
                const LOAD_MORE_INCREMENT = 4 //common row
                const GROUPS = {
                    1: 'One',
                    2: 'Two',
                    3: 'Three',
                    4: 'Four'
                }

                var cb83 = $(".cb83-article-finder-container").first();

                if (cb83 === undefined || cb83.length === 0) {
                    return;
                }

                // toggle dropdowns
                $(DROPDOWN_TRIGGER_SELECTOR).on('click', function (e) {
                    const containerParent = $(this).closest(CONTAINER_SELECTOR);
                    const thisParent = $(this).parent();

                    //already open, then close
                    if (thisParent.hasClass(OPEN_CLASS)) {
                        //close dropdown
                        thisParent.find(CB83_DROPDOWN_SELECTOR).slideUp();
                        thisParent.removeClass(OPEN_CLASS);
                    } else {
                        //closed, then open

                        // slide up all container children dropdowns
                        containerParent.find(CB83_DROPDOWN_SELECTOR).slideUp();

                        // remove all children class with open
                        containerParent.find(DROPDOWN_SELECTOR).removeClass(OPEN_CLASS);

                        // add open class for this parent
                        thisParent.addClass(OPEN_CLASS);

                        //open dropdown
                        thisParent.find(CB83_DROPDOWN_SELECTOR).slideDown();
                    }
                })

                //close dropdown from parent
                $(CLOSE_BUTTON_SELECTOR).on('click', function (e) {
                    const parentTitleSelector = $(this).closest(OPEN_SELECTOR)
                    parentTitleSelector.removeClass(OPEN_CLASS)
                    $(this).closest(CB83_DROPDOWN_SELECTOR).slideUp();
                })

                $(CONTAINER_SELECTOR).find('.filter-item > input[type="checkbox"]').on('click', (event) => {
                    var checked = $(event.target).parents(".cb83-line-items").find('input:checked');
                    var filterTitle = $(event.target).parents(DROPDOWN_SELECTOR).find(DROPDOWN_TRIGGER_SELECTOR)
                    if (checked.length > 0) {
                        $(event.target).parents(DROPDOWN_SELECTOR).find('.numSelected').text('(' + checked.length + ')');
                        $(filterTitle).removeClass(NO_RESULTS_CLASS)
                        return;
                    }
                    $(filterTitle).addClass(NO_RESULTS_CLASS)
                    $(event.target).parents(DROPDOWN_SELECTOR).find('.numSelected').text('');
                });


                $(cb83).find('.cb83-show-results').on('click', (event) => {
                    var data = getDefaultDataObject(1);

                    //find all checked options
                    var checked = $(cb83).find('input:checked');
                    for (var i = 0; i < checked.length; i++) {
                        var group = GROUPS[$(checked[i]).attr('data-group-id')];
                        var value = $(checked[i]).attr('data-sitecore-id');
                        data['filterBy'][group].push(value);
                    }
                    filter(data);
                });
                $(cb83).find('.cb83-clear-all').on('click', (event) => {
                    var checked = $(cb83).find('input:checked');
                    $(checked).prop('checked', false);

                    $(cb83).find(DROPDOWN_SELECTOR).find('.cb83-filter-title').addClass('no-results')
                    $(cb83).find(DROPDOWN_SELECTOR).find('.numSelected').text('');

                    var data = getDefaultDataObject(1);
                    filter(data);
                });
                $(cb83).find(LOAD_MORE_BUTTON).on('click', () => {
                    var pageNumber = $(cb83).find(FEED_CTA_SELECTOR).attr('data-page');
                    var data = getDefaultDataObject(pageNumber);

                    //find all checked options
                    var checked = $(cb83).find('input:checked');
                    for (var i = 0; i < checked.length; i++) {
                        var group = GROUPS[$(checked[i]).attr('data-group-id')];
                        var value = $(checked[i]).attr('data-sitecore-id');
                        data['filterBy'][group].push(value);
                    }

                    var nextPageNumber = parseInt(pageNumber) + 1;
                    more(data, nextPageNumber)

                });

                function filter(postdata) {
                    $(cb83).find(CB83_PARENT).empty();
                    $(cb83).find(RESULTS_CONTAINER).text("");
                    //make API request
                    var post = $.post('/solution-finder/filter', postdata);
                    post.done(function (data) {
                        var template_b = $('#cb85-tile-b').html();
                        var template_dark = $('#cb85-tile-dark').html();
                        var template_double = $('#cb85-tile-double').html();
                        var template_video = $('#cb85-tile-video').html();
                        var template_double_video = $('#cb85-tile-double-video').html();
                        
                        for (var i = 0; i < data.Articles.length; i++) {
                            var result = "";
                            var articleData = data.Articles[i];
                            var isVideoTile = articleData.VideoUrl !== "";
                            
                            switch (i) {
                                case 3:
                                    //dark tile
                                    result = Mustache.to_html(template_dark, articleData);
                                    break;

                                case 4:
                                    if (isVideoTile) {
                                        //double video
                                        result = Mustache.to_html(template_double_video, articleData);
                                        break;
                                    }
                                    //double tile
                                    result = Mustache.to_html(template_double, articleData);
                                    break;

                                default:
                                    //regular tile
                                    if (isVideoTile) {
                                        //double video
                                        result = Mustache.to_html(template_video, articleData);
                                        break;
                                    }
                                    result = Mustache.to_html(template_b, articleData);
                                    break;
                            }

                            $(cb83).find(CB83_PARENT).append(result);
                            continue;
                        }

                        $(cb83).find(FEED_CTA_SELECTOR).first().attr('data-page', 1);
                        

                        if (data.ArticlesFound > 0) {
                            var totalResultsText = (data.ArticlesFound + data.Articles.length) + " total result";
                            if (data.ArticlesFound > 1) totalResultsText += "s";

                            $(cb83).find(RESULTS_CONTAINER).text(totalResultsText);
                            $(cb83).find(LOAD_MORE_BUTTON).removeClass('hidden')
                            $(cb83).find(LOAD_MORE_BUTTON).text('Show more (' + data.ArticlesFound + ')');
                        }
                        else {
                            var totalResultsText = data.Articles.length + " total result";
                            if (data.ArticlesFound != 1) totalResultsText += "s";

                            $(cb83).find(RESULTS_CONTAINER).text(totalResultsText);
                            $(cb83).find(LOAD_MORE_BUTTON).addClass('hidden')
                            $(cb83).find(LOAD_MORE_BUTTON).text('Show more (0)');
                        }
                        canonHelper.constructVideoElement();
                    });
                }
                function more(postdata, nextPageNumber) {
                    //make API request
                    var post = $.post('/solution-finder/more', postdata);
                    post.done(function (data) {
                        if (data.Articles.length == 0)
                            return;

                        var template_b = $('#cb85-tile-b').html();
                        var template_dark = $('#cb85-tile-dark').html();
                        var template_double = $('#cb85-tile-double').html();
                        var template_video = $('#cb85-tile-video').html();
                        var template_double_video = $('#cb85-tile-double-video').html();
                        var isEven = nextPageNumber % 2 == 0;
                        
                        for (var i = 0; i < data.Articles.length; i++) {
                            var result = "";
                            var articleData = data.Articles[i];
                            var isVideoTile = articleData.VideoUrl !== "";
                            if (isEven) {
                                switch (i) {
                                    case 0:
                                        //dark tile
                                        result = Mustache.to_html(template_dark, articleData);
                                        break;

                                    case 6:
                                        if (isVideoTile) {
                                            //double video
                                            result = Mustache.to_html(template_double_video, articleData);
                                            break;
                                        }
                                        //double tile
                                        result = Mustache.to_html(template_double, articleData);
                                        break;

                                    default:
                                        //regular tile
                                        if (isVideoTile) {
                                            //double video
                                            result = Mustache.to_html(template_video, articleData);
                                            break;
                                        }
                                        result = Mustache.to_html(template_b, articleData);
                                        break;
                                }

                                $(cb83).find(CB83_PARENT).append(result);
                                continue;
                            }
                            switch (i) {
                                case 3:
                                    //dark tile
                                    result = Mustache.to_html(template_dark, articleData);
                                    break;

                                case 4:
                                    if (isVideoTile) {
                                        //double video
                                        result = Mustache.to_html(template_double_video, articleData);
                                        break;
                                    }
                                    //double tile
                                    result = Mustache.to_html(template_double, articleData);
                                    break;

                                default:
                                    //regular tile
                                    if (isVideoTile) {
                                        //double video
                                        result = Mustache.to_html(template_video, articleData);
                                        break;
                                    }
                                    result = Mustache.to_html(template_b, articleData);
                                    break;
                            }

                            $(cb83).find(CB83_PARENT).append(result);
                            continue;
                        }

                        


                        $(cb83).find(FEED_CTA_SELECTOR).attr('data-page', nextPageNumber);

                        if (data.ArticlesFound > 0) {
                            $(cb83).find(LOAD_MORE_BUTTON).removeClass('hidden')
                            $(cb83).find(LOAD_MORE_BUTTON).text('Show more (' + data.ArticlesFound + ')');
                        }
                        else {
                            $(cb83).find(LOAD_MORE_BUTTON).addClass('hidden')
                            $(cb83).find(LOAD_MORE_BUTTON).text('Show more (0)');
                        }
                        canonHelper.constructVideoElement();
                    });
                }

                function getDefaultDataObject(pageNumber) {
                    return {
                        'articleLocations': $(cb83).attr('data-article-locations'),
                        'type': 'article',
                        'pageNumber': pageNumber,
                        'more': 'article',
                        'filterBy': {
                            'One': [],
                            'Two': [],
                            'Three': [],
                            'Four': []
                        }
                    }
                }

                $('html').on('click', function (e) {
                    e.stopPropagation();
                    const target = $(e.target)
                    if (!target.hasClass(DROPDOWN_TRIGGER_CLASS) && !target.parents(CB83_DROPDOWN_SELECTOR).length) {
                        if ($(DROPDOWN_SELECTOR).hasClass(OPEN_CLASS)) {
                            $(OPEN_SELECTOR).removeClass(OPEN_CLASS)
                            $(CB83_DROPDOWN_SELECTOR).slideUp();
                        }
                    }
                });
            },
            InitCB84SolutionFinder: function () {
                //DROP DOWN RELATED
                const CONTAINER_SELECTOR = '.cb84-filters';
                const DROPDOWN_TRIGGER_CLASS = 'cb84-filter-title';
                const DROPDOWN_TRIGGER_SELECTOR = `.${DROPDOWN_TRIGGER_CLASS}`;
                const OPEN_CLASS = 'open-dropdown';
                const OPEN_SELECTOR = `.${OPEN_CLASS}`;
                const CB84_DROPDOWN_SELECTOR = '.cb84-dropdown';
                const NO_RESULTS_CLASS = 'no-results';
                const CLOSE_BUTTON_SELECTOR = '.cb84-close-dropdown';
                const DROPDOWN_SELECTOR = '.cb84-dropdown-box';
                const FEED_CTA_SELECTOR = '.cb84-feed-cta';
                $(CB84_DROPDOWN_SELECTOR).hide();
                //FEED RELATED
                const CB84_FEED_CONTAINER = '.cb84-solution-finder-result-container'
                const CB84_PARENT = '.cb84-tiles-container'
                const CB84_LOAD_MORE_BUTTON = '.cb84-more'
                const CB84_LOAD_MORE_INCREMENT = 4 //common row
                const GROUPS = {
                    1: 'One',
                    2: 'Two',
                    3: 'Three',
                    4: 'Four'
                }

                var cb84 = $(".cb84-solution-finder-container").first();

                if (cb84 === undefined || cb84.length === 0) {
                    return;
                }

                // toggle dropdowns
                $(DROPDOWN_TRIGGER_SELECTOR).on('click', function (e) {
                    const containerParent = $(this).closest(CONTAINER_SELECTOR);
                    const thisParent = $(this).parent();

                    //already open, then close
                    if (thisParent.hasClass(OPEN_CLASS)) {
                        //close dropdown
                        thisParent.find(CB84_DROPDOWN_SELECTOR).slideUp();
                        thisParent.removeClass(OPEN_CLASS);
                    } else {
                        //closed, then open

                        // slide up all container children dropdowns
                        containerParent.find(CB84_DROPDOWN_SELECTOR).slideUp();

                        // remove all children class with open
                        containerParent.find(DROPDOWN_SELECTOR).removeClass(OPEN_CLASS);

                        // add open class for this parent
                        thisParent.addClass(OPEN_CLASS);

                        //open dropdown
                        thisParent.find(CB84_DROPDOWN_SELECTOR).slideDown();
                    }
                })

                //close dropdown from parent
                $(CLOSE_BUTTON_SELECTOR).on('click', function (e) {
                    const parentTitleSelector = $(this).closest(OPEN_SELECTOR)
                    parentTitleSelector.removeClass(OPEN_CLASS)
                    $(this).closest(CB84_DROPDOWN_SELECTOR).slideUp();
                })

                $(CONTAINER_SELECTOR).find('.filter-item > input[type="checkbox"]').on('click', (event) => {
                    var checked = $(event.target).parents(".cb84-line-items").find('input:checked');
                    var filterTitle = $(event.target).parents(DROPDOWN_SELECTOR).find(DROPDOWN_TRIGGER_SELECTOR)
                    if (checked.length > 0) {
                        $(event.target).parents(DROPDOWN_SELECTOR).find('.numSelected').text('(' + checked.length + ')');
                        $(filterTitle).removeClass(NO_RESULTS_CLASS)
                        return;
                    }
                    $(filterTitle).addClass(NO_RESULTS_CLASS)
                    $(event.target).parents(DROPDOWN_SELECTOR).find('.numSelected').text('');
                });

                $(cb84).find('.cb84-show-results').on('click', (event) => {
                    var data = getDefaultDataObject(1, '');                    

                    //find all checked options
                    var checked = $(cb84).find('input:checked');
                    for (var i = 0; i < checked.length; i++) {
                        var group = GROUPS[$(checked[i]).attr('data-group-id')];
                        var value = $(checked[i]).attr('data-sitecore-id');
                        data['filterBy'][group].push(value);
                    }

                    filter(data);

                });
                $(cb84).find('.cb84-clear-all').on('click', (event) => {
                    var checked = $(cb84).find('input:checked');
                    $(checked).prop('checked', false);

                    $(cb84).find(DROPDOWN_SELECTOR).find(DROPDOWN_TRIGGER_SELECTOR).addClass(NO_RESULTS_CLASS)
                    $(cb84).find(DROPDOWN_SELECTOR).find('.numSelected').text('');

                    var data = getDefaultDataObject(1, '');
                    filter(data);
                });

                $(cb84).find('#cb84-solutions-more').on('click', (event) => {
                    var pageNumber = $(event.target).parent(FEED_CTA_SELECTOR).attr('data-page');
                    var nextPageNumber = parseInt(pageNumber) + 1;
                    var data = getDefaultDataObject(pageNumber, 'solutions');

                    //find all checked options
                    var checked = $(cb84).find('input:checked');
                    for (var i = 0; i < checked.length; i++) {
                        var group = GROUPS[$(checked[i]).attr('data-group-id')];
                        var value = $(checked[i]).attr('data-sitecore-id');
                        data['filterBy'][group].push(value);
                    }

                    var container = $(cb84).find(CB84_PARENT).first();
                    var cta = $(cb84).find(FEED_CTA_SELECTOR).first();
                    var template = $('#cb85-tile').html();
                    var nextPageNumber = parseInt(pageNumber) + 1;
                    more(data, container, cta, template, nextPageNumber)
                });
                $(cb84).find('#cb84-case-studies-more').on('click', (event) => {
                    var pageNumber = $(event.target).parent(FEED_CTA_SELECTOR).attr('data-page');
                    var data = getDefaultDataObject(pageNumber, 'case-studies');

                    //find all checked options
                    var checked = $(cb84).find('input:checked');
                    for (var i = 0; i < checked.length; i++) {
                        var group = GROUPS[$(checked[i]).attr('data-group-id')];
                        var value = $(checked[i]).attr('data-sitecore-id');
                        data['filterBy'][group].push(value);
                    }

                    var container = $(cb84).find(CB84_PARENT).last();
                    var cta = $(cb84).find(FEED_CTA_SELECTOR).last();
                    var template = $('#cb85-tile-b').html();
                    var nextPageNumber = parseInt(pageNumber) + 1;
                    more(data, container, cta, template, nextPageNumber)
                    
                });

                function filter(data) {
                    //make API request
                    var post = $.post('/solution-finder/filter', data);
                    post.done(function (data) {
                        var template = $('#cb85-tile').html();
                        var result = Mustache.to_html(template, data);
                        $(cb84).find(CB84_PARENT).first().html(result);
                        $(cb84).find(FEED_CTA_SELECTOR).first().attr('data-page', 1);
                        if (data.SolutionsFound > 0) {
                            $(cb84).find(FEED_CTA_SELECTOR).first().find(CB84_LOAD_MORE_BUTTON).removeClass('hidden')
                            $(cb84).find(FEED_CTA_SELECTOR).first().find(CB84_LOAD_MORE_BUTTON).text('Show more (' + data.SolutionsFound + ')');
                        }
                        else {
                            $(cb84).find(FEED_CTA_SELECTOR).first().find(CB84_LOAD_MORE_BUTTON).addClass('hidden')
                            $(cb84).find(FEED_CTA_SELECTOR).first().find(CB84_LOAD_MORE_BUTTON).text('Show more (0)');
                        }

                        var template = $('#cb85-tile-b').html();
                        var result = Mustache.to_html(template, data);
                        $(cb84).find(CB84_PARENT).last().html(result);
                        $(cb84).find(FEED_CTA_SELECTOR).last().attr('data-page', 1);
                        if (data.CaseStudiesFound > 0) {
                            $(cb84).find(FEED_CTA_SELECTOR).last().find(CB84_LOAD_MORE_BUTTON).removeClass('hidden')
                            $(cb84).find(FEED_CTA_SELECTOR).last().find(CB84_LOAD_MORE_BUTTON).text('Show more (' + data.CaseStudiesFound + ')');
                        }
                        else {
                            $(cb84).find(FEED_CTA_SELECTOR).last().find(CB84_LOAD_MORE_BUTTON).addClass('hidden')
                            $(cb84).find(FEED_CTA_SELECTOR).last().find(CB84_LOAD_MORE_BUTTON).text('Show more (0)');
                        }
                    });
                }
                function more(data, container, cta, template, nextPageNumber) {
                    //make API request
                    var post = $.post('/solution-finder/more', data);
                    post.done(function (data) {
                        var result = Mustache.to_html(template, data);
                        $(container).append(result);
                        $(cta).attr('data-page', nextPageNumber);

                        if (data.ArticlesFound > 0) {
                            $(cta).find(CB84_LOAD_MORE_BUTTON).removeClass('hidden')
                            $(cta).find(CB84_LOAD_MORE_BUTTON).text('Show more (' + data.ArticlesFound + ')');
                        }
                        else {
                            $(cta).find(CB84_LOAD_MORE_BUTTON).addClass('hidden')
                            $(cta).find(CB84_LOAD_MORE_BUTTON).text('Show more (0)');
                        }
                    });
                }

                function getDefaultDataObject(pageNumber, more) {
                    return {
                        'articleLocations': $(cb84).attr('data-article-locations'),
                        'type': 'solution',
                        'pageNumber': pageNumber,
                        'more': more,
                        'filterBy': {
                            'One': [],
                            'Two': [],
                            'Three': [],
                            'Four': []
                        }
                    }
                }

                $('html').on('click', function (e) {
                    e.stopPropagation();
                    const target = $(e.target)
                    if (!target.hasClass(DROPDOWN_TRIGGER_CLASS) && !target.parents(CB84_DROPDOWN_SELECTOR).length) {
                        if ($(DROPDOWN_SELECTOR).hasClass(OPEN_CLASS)) {
                            $(OPEN_SELECTOR).removeClass(OPEN_CLASS)
                            $(CB84_DROPDOWN_SELECTOR).slideUp();
                        }
                    }
                });
            },
            InitCB79SquareFeed: function () {
                //initiate CONST's
                const CONTAINER_CLASS = '.cb79-square-feed-container'
                const SLIDER_CLASS = '.cb79-square-slider'
                const SLIDER_CONTAINER_CLASS = '.slider-tabs'
                const TAB_ID_PREFIX = "cb79-square-tiles-"
                const SLIDER_TAB_CLASS = '.tab'
                const SELECTOR_TAB_CLASS = `${SLIDER_CLASS} > ${SLIDER_CONTAINER_CLASS} > ${SLIDER_TAB_CLASS}`;
                const SLICK_TAB_CLASS = '.cb79-slider';
                const NO_ARROW_CLASS = '.no-arrows'
                const SLICK_TAB_ARROW_CLASS = `${CONTAINER_CLASS} > .arrow`;
                const TAB_ON_CLASS = 'on'
                const SINGLE_LINE_CLASS = 'single-line'
                const MOBILE_ONLY_SLICK_CLASS = `${CONTAINER_CLASS}${NO_ARROW_CLASS} > ${SLIDER_CLASS} > ${SLICK_TAB_CLASS}.${TAB_ON_CLASS}`

                var cb79 = $(CONTAINER_CLASS).first();

                if (cb79 === undefined || cb79.length === 0) {
                    return;
                }

                const alignSlider = () => {

                    const activeSlickSelector = `${CONTAINER_CLASS} ${SLICK_TAB_CLASS}.${TAB_ON_CLASS}`

                    $(document).find(activeSlickSelector).each(function () {
                        const dots = $(this).find('.slick-dots > li').children().length
                        if (dots === 0) {
                            $(this).parent(SLIDER_CLASS).siblings(SLICK_TAB_ARROW_CLASS).addClass('hidden')
                        } else {
                            $(this).parent(SLIDER_CLASS).siblings(SLICK_TAB_ARROW_CLASS).removeClass('hidden')
                            $(this).find('.slick-dots')
                                .attr('style', `display: grid !important; grid-template-columns: repeat(${dots}, 1fr) !important`);
                        }
                    })
                }

                function afterSlickChangeEvents(e, slick, currentSlide) {
                    const trueCurrentSlide = parseInt(currentSlide + 1)
                    const slickDots = slick.$dots && slick.$dots[0] ? slick.$dots[0].childElementCount : 0;

                    if (currentSlide >= 1) {
                        $(e.currentTarget).parent(SLIDER_CLASS).siblings('.left').addClass('active')
                    } else {
                        $(e.currentTarget).parent(SLIDER_CLASS).siblings('.left').removeClass('active')
                    }
                    if (trueCurrentSlide === slickDots) {
                        $(e.currentTarget).parent(SLIDER_CLASS).siblings('.right').removeClass('active')
                    } else {
                        $(e.currentTarget).parent(SLIDER_CLASS).siblings('.right').addClass('active')
                    }
                }

                const cb79SlickOptions = (single) => ({
                    infinite: false,
                    slidesToShow: single ? 4 : 5,
                    slidesToScroll: 1,
                    autoplay: false,
                    autoplaySpeed: 3000,
                    dots: true,
                    pauseOnDotsHover: true,
                    adaptiveHeight: true,
                    swipeToSlide: true,
                    mobileFirst: false,
                    arrows: false,
                })


                const cb79StandardBreakpoints = [{ breakpoint: 1300, settings: { slidesToShow: 5 } },
                { breakpoint: 1200, settings: { slidesToShow: 4 } },
                { breakpoint: 1010, settings: { slidesToShow: 5 } },
                { breakpoint: 860, settings: { slidesToShow: 4 } },
                { breakpoint: 705, settings: { slidesToShow: 3 } },
                { breakpoint: 542, settings: { slidesToShow: 2 } },
                { breakpoint: 510, settings: { slidesToShow: 1 } },
                ]

                const cb79SingleLineBreakpoints = [{ breakpoint: 1300, settings: { slidesToShow: 4 } },
                { breakpoint: 1200, settings: { slidesToShow: 4 } },
                { breakpoint: 1010, settings: { slidesToShow: 5 } },
                { breakpoint: 860, settings: { slidesToShow: 4 } },
                { breakpoint: 705, settings: { slidesToShow: 3 } },
                { breakpoint: 542, settings: { slidesToShow: 2 } },
                { breakpoint: 510, settings: { slidesToShow: 1 } },
                ]

                //slick bootstrap for desktop slick version
                function bootstrapSlick() {
                    $(`${CONTAINER_CLASS}:not(${NO_ARROW_CLASS}) > ${SLIDER_CLASS} > ${SLICK_TAB_CLASS}.${TAB_ON_CLASS}`).not('.slick-initialized').slick({
                        ...cb79SlickOptions(),
                        responsive: cb79StandardBreakpoints
                    }).on('afterChange', (e, slick, currentSlide, nextSlide) => {
                        afterSlickChangeEvents(e, slick, currentSlide)
                    });
                }

                function bootstrapSlickMobileOnly() {

                    if (window.innerWidth <= 1200) {
                        $(MOBILE_ONLY_SLICK_CLASS).not('.slick-initialized').slick({
                            ...cb79SlickOptions($(this).hasClass(SINGLE_LINE_CLASS)),
                            responsive: $(this).hasClass(SINGLE_LINE_CLASS) ? cb79SingleLineBreakpoints : cb79StandardBreakpoints
                        }).on('afterChange', (e, slick, currentSlide, nextSlide) => {
                            afterSlickChangeEvents(e, slick, currentSlide)
                        });
                    } else {
                        if ($(MOBILE_ONLY_SLICK_CLASS)) $(MOBILE_ONLY_SLICK_CLASS).slick('unslick');
                    }
                }

                $(SLICK_TAB_CLASS).on('init', function (event, slick) {
                    //dynamic dots
                    const dots = slick.$dots && slick.$dots[0] ? slick.$dots[0].childElementCount : 0
                    $(this).find('.slick-dots')
                        .attr('style', `display: grid !important; grid-template-columns: repeat(${dots}, 1fr) !important`)
                    dots === 0 ? $(SLICK_TAB_ARROW_CLASS).addClass('hidden') : $(SLICK_TAB_ARROW_CLASS).removeClass('hidden')
                });

                //event listeners
                $(`${CONTAINER_CLASS} > .left`).click(function (e) {
                    $(this).siblings(SLIDER_CLASS).find(`> .${TAB_ON_CLASS}`).slick('slickPrev');
                });
                $(`${CONTAINER_CLASS} > .right`).click(function (e) {
                    $(this).siblings(SLIDER_CLASS).find(`> .${TAB_ON_CLASS}`).slick('slickNext');
                });

                let onResizeTimer = null;

                //dynamic slider
                $(window).on('resize orientationChange', function (e) {
                    if (onResizeTimer !== null) {
                        clearTimeout(onResizeTimer)
                    }
                    onResizeTimer = setTimeout(() => {
                        //slider dots
                        $(SLIDER_CLASS).each(function () {
                            const dots = $(this).find('.slick-dots > li').children().length
                            if (dots === 0) {
                                $(SLICK_TAB_ARROW_CLASS).addClass('hidden')
                            } else {
                                $(SLICK_TAB_ARROW_CLASS).removeClass('hidden')
                                $(this).find('.slick-dots')
                                    .attr('style', `display: grid !important; grid-template-columns: repeat(${dots}, 1fr) !important`);
                            }
                        });
                        onResizeTimer = null;
                        //toggle mobile slick - add this for no slick on desktop versions (i.e. not c & d variants)
                        bootstrapSlickMobileOnly()
                    },
                        100)
                });


                // string
                $(SELECTOR_TAB_CLASS).on('click', (e) => {
                    e.stopPropagation()

                    if ($(e.target).hasClass(TAB_ON_CLASS)) return;
                    const closestSlick = $(e.target).parents(CONTAINER_CLASS).find(`${SLICK_TAB_CLASS}.${TAB_ON_CLASS}`)
                    const matchingSliderIndex = $(`.${TAB_ID_PREFIX}${e.target.dataset.index}`);


                    // important, sitecore should never have the same ID's for these, it will result in errors
                    if (closestSlick) {
                        closestSlick.slick('unslick');
                        $(e.target).siblings(SLIDER_TAB_CLASS).removeClass(TAB_ON_CLASS)
                        $(e.target).addClass(TAB_ON_CLASS);
                        closestSlick.removeClass(TAB_ON_CLASS);
                        const childMatch = $(e.target).parents(CONTAINER_CLASS).find(matchingSliderIndex)
                        childMatch.addClass(TAB_ON_CLASS);
                    }


                    //choose relevant one for sitecore
                    bootstrapSlick()
                    alignSlider()

                })

                $(window).on('load', function (e) {
                    //initiate both (should choose one of these for sitecore)
                    bootstrapSlick()
                    bootstrapSlickMobileOnly()
                    alignSlider()
                });
            },
            InitCB72SubCategoryFeatures: function () {
                const activeClass = 'activeClass';
                const HMCB_CB72_MENU_WRAPPER = '.cb72-menu-wrapper'
                const HMCB_CB72 = '.cb72-menu-item'
                const HMCB_CONTENT_CONTAINER = '.cb72-menu-content-container';
                const HMCB_CLOSE = '.cb72-close ';
                const MOBILE_CLASS = 'cb72-mobile';

                //responsive breakpoints
                const CB72_BREAKPOINTS = {
                    cb72_five: 1200,
                    cb72_four: 1000,
                    cb72_three: 800,
                    cb72_two: 720,
                }

                var cb72 = $(HMCB_CB72).first();

                if (cb72 === undefined || cb72.length === 0) {
                    return;
                }

                const closeCB72 = (contentContainerSelection, nearestActiveMenuItem) => {
                    contentContainerSelection.css("display", "none");
                    nearestActiveMenuItem.removeClass(activeClass);
                }

                //click active menu
                $(HMCB_CB72).on('click', function () {

                    if ($(this).hasClass(activeClass)) {
                        const newThis = $(this)
                        const nearestContentContainer = newThis.siblings(HMCB_CONTENT_CONTAINER);
                        const nearestActiveMenuItem = newThis.closest(HMCB_CB72_MENU_WRAPPER).find(`${HMCB_CB72}.${activeClass}`);
                        const contentContainerSelection = newThis.closest(HMCB_CB72_MENU_WRAPPER).find(HMCB_CONTENT_CONTAINER);
                        nearestContentContainer.css("display", "block").promise().done(() => {
                            newThis.removeClass(activeClass);
                        });
                        closeCB72(contentContainerSelection, nearestActiveMenuItem);

                    } else {
                        const newThis = $(this)
                        const nearestContentContainer = newThis.siblings(HMCB_CONTENT_CONTAINER);
                        const nearestActiveMenuItem = newThis.closest(HMCB_CB72_MENU_WRAPPER).find(`${HMCB_CB72}.${activeClass}`);
                        const contentContainerSelection = newThis.closest(HMCB_CB72_MENU_WRAPPER).find(HMCB_CONTENT_CONTAINER);

                        closeCB72(contentContainerSelection, nearestActiveMenuItem);

                        nearestContentContainer.css("display", "block").promise().done(() => {
                            newThis.addClass(activeClass);
                        });
                    }

                    closeCB72(contentContainerSelection, nearestActiveMenuItem);

                });


                $(HMCB_CLOSE).on('click', function () {
                    const contentContainerSelection = $(this).parents(HMCB_CONTENT_CONTAINER)
                    const nearestActiveMenuItem = contentContainerSelection.siblings(`${HMCB_CB72}.${activeClass}`)
                    closeCB72(contentContainerSelection, nearestActiveMenuItem);
                });

                const assignResponsiveClass = () => {

                    const documentWidth = window.innerWidth || document.body.clientWidth || document.documentElement.clientWidth || screen.width;

                    for (const breakpointClass in CB72_BREAKPOINTS) {
                        const breakpointWidth = CB72_BREAKPOINTS[breakpointClass];

                        if (documentWidth <= breakpointWidth) {
                            $(`.${breakpointClass}:not(.${MOBILE_CLASS})`).addClass(MOBILE_CLASS)
                        } else {
                            $(`.${breakpointClass}`).removeClass(MOBILE_CLASS)
                        }
                    }
                }

                //initiate this call
                assignResponsiveClass()

                //watch for resize of screen to add these classes
                window.addEventListener('resize', $.throttle(280, () => {
                    assignResponsiveClass();
                }), true);

            },
            InitCB63SubCategoryNavigation: function () {
                const HMCB_CB63 = ".cb63";
                const SCROLL_LEFT = ".scroll-left";
                const SCROLL_RIGHT = ".scroll-right";
                const SCROLL_ENABLED = "scroll-enabled"
                const SCROLL_REQUIRED = "scroll-required"
                const SCROLL_LINKS = ".cb63-menu-items"

                var cb63 = $(HMCB_CB63).first();

                if (cb63 === undefined || cb63.length === 0) {
                    return;
                }

                updateScrollArrows = function () {
                    const scrollLinks = $(HMCB_CB63).find(SCROLL_LINKS)[0];
                    const maxScrollLeft = scrollLinks.scrollWidth - scrollLinks.clientWidth;
                    if ($(HMCB_CB63).find(SCROLL_LINKS)[0].scrollLeft === 0) {
                        $(HMCB_CB63).find(SCROLL_LEFT).removeClass(SCROLL_ENABLED)
                        $(HMCB_CB63).find(SCROLL_RIGHT).addClass(SCROLL_ENABLED)
                    } else if (Math.trunc($(HMCB_CB63).find(SCROLL_LINKS)[0].scrollLeft) >= (maxScrollLeft - 1)) {
                        $(HMCB_CB63).find(SCROLL_LEFT).addClass(SCROLL_ENABLED);
                        $(HMCB_CB63).find(SCROLL_RIGHT).removeClass(SCROLL_ENABLED);
                    } else {
                        $(HMCB_CB63).find(SCROLL_LEFT).addClass(SCROLL_ENABLED);
                        $(HMCB_CB63).find(SCROLL_RIGHT).addClass(SCROLL_ENABLED);
                    }
                }

                configureScrollLinks = function () {
                    const scroll_links = $(HMCB_CB63).find(SCROLL_LINKS);
                    if (scroll_links !== undefined && scroll_links.length > 0) {
                        if ($(HMCB_CB63).find(SCROLL_LINKS)[0].scrollWidth > $(HMCB_CB63).find(SCROLL_LINKS)[0].clientWidth) {
                            $(HMCB_CB63).find(SCROLL_LEFT).addClass(SCROLL_REQUIRED);
                            $(HMCB_CB63).find(SCROLL_RIGHT).addClass(SCROLL_REQUIRED);
                            $(HMCB_CB63).addClass(SCROLL_REQUIRED);
                        } else {
                            $(HMCB_CB63).find(SCROLL_LEFT).removeClass(SCROLL_REQUIRED).removeClass(SCROLL_ENABLED);
                            $(HMCB_CB63).find(SCROLL_RIGHT).removeClass(SCROLL_REQUIRED).removeClass(SCROLL_ENABLED);
                            $(HMCB_CB63).removeClass(SCROLL_REQUIRED);
                            updateScrollArrows();
                        }
                    }
                }
                configureScrollLinks()

                window.addEventListener('resize', $.throttle(280, () => {
                    // $.throttle(280, () => { configureScrollLinks() } );
                    configureScrollLinks();
                }), true);
                window.addEventListener('scroll', () => {
                    updateScrollArrows()
                }, true);

                $(HMCB_CB63).find(SCROLL_LEFT).on('click', function (e) {
                    const scrollLinks = $(HMCB_CB63).find(SCROLL_LINKS)[0];
                    scrollLinks.scrollLeft -= (50);
                    e.preventDefault();
                    updateScrollArrows();
                })
                $(HMCB_CB63).find(SCROLL_RIGHT).on('click', function (e) {
                    const scrollLinks = $(HMCB_CB63).find(SCROLL_LINKS)[0];
                    scrollLinks.scrollLeft += (50);
                    e.preventDefault();
                    updateScrollArrows();
                })


            },
            InitCB56KeySpecifications: function () {
                var cb56 = $('.cb56').first();
                if (cb56 === undefined || cb56.length === 0) {
                    return;
                }

                $('.cb56 .arrow-container').on("click", function (e) {

                    const collapsedPanel = $(this).hasClass('panel-collapsed')

                    if (collapsedPanel) {
                        // expand the panel
                        $(this).parents('.cb56').find('.collapsein').slideDown().promise().done(() => {
                                $(this).removeClass('panel-collapsed')
                                $(this).toggleClass("up");
                            })

                            ;
                    } else {
                        // collapse the panel
                        $(this).parents('.cb56').find('.collapsein').slideUp().promise().done(() => {
                            $(this).addClass('panel-collapsed');
                            $(this).toggleClass("up");
                        })

                    }

                });

                $(window).on('resize orientationChange', function (e) {
                    $('.cb56 .arrow-container').removeClass('panel-collapsed')
                    $('.cb56 .arrow-container').addClass("up")
                    $('.cb56').find('.collapsein').slideDown();
                });
            },
            InitCB82ProductVariants: function () {
                const CONTAINER_CLASS = '.cb82-product-variant-feed'
                const SLIDER_CLASS = '.cb82-slider'
                const SLIDER_CONTAINER_CLASS = '.slider-tabs'
                const TAB_ID_PREFIX = "cb82-slider-container-"
                const TAB_ON_CLASS = 'on'
                const SLIDER_TAB_CLASS = '.tab'
                const SELECTOR_TAB_CLASS = `${SLIDER_CLASS} > ${SLIDER_CONTAINER_CLASS} > ${SLIDER_TAB_CLASS}`;
                const SLICK_TAB_CLASS = '.cb82-slider-container';
                const SLICK_TAB_ARROW_CLASS = `${CONTAINER_CLASS} > .arrow`;

                const cb82 = $(CONTAINER_CLASS).first();
                if (cb82 === undefined || cb82.length === 0) {
                    return;
                }

                function afterSlickChangeEvents(e, slick, currentSlide) {
                    const trueCurrentSlide = parseInt(currentSlide + 1)
                    const slickDots = slick.$dots && slick.$dots[0] ? slick.$dots[0].childElementCount : 0;

                    if (currentSlide >= 1) {
                        $(e.currentTarget).parent(SLIDER_CLASS).siblings('.left').addClass('active')
                    } else {
                        $(e.currentTarget).parent(SLIDER_CLASS).siblings('.left').removeClass('active')
                    }
                    if (trueCurrentSlide === slickDots) {
                        $(e.currentTarget).parent(SLIDER_CLASS).siblings('.right').removeClass('active')
                    } else {
                        $(e.currentTarget).parent(SLIDER_CLASS).siblings('.right').addClass('active')
                    }
                }

                const cb82SlickOptions = () => ({
                    infinite: false,
                    slidesToShow: 4,
                    slidesToScroll: 1,
                    autoplay: false,
                    autoplaySpeed: 3000,
                    dots: true,
                    pauseOnDotsHover: true,
                    adaptiveHeight: true,
                    swipeToSlide: true,
                    mobileFirst: false,
                    arrows: false,
                })


                const cb79StandardBreakpoints = [{ breakpoint: 1320, settings: { slidesToShow: 3 } },
                { breakpoint: 1035, settings: { slidesToShow: 3 } },
                { breakpoint: 1020, settings: { slidesToShow: 2 } },
                { breakpoint: 730, settings: { slidesToShow: 1 } },
                ]

                //slick bootstrap for desktop slick version
                function bootstrapSlick() {
                    $(`${CONTAINER_CLASS} > ${SLIDER_CLASS} > ${SLICK_TAB_CLASS}.${TAB_ON_CLASS}`).not('.slick-initialized').slick({
                        ...cb82SlickOptions(),
                        responsive: cb79StandardBreakpoints
                    }).on('afterChange', (e, slick, currentSlide, nextSlide) => {
                        afterSlickChangeEvents(e, slick, currentSlide)
                    });
                }

                //initiate both (should choose one of these for sitecore)
                bootstrapSlick()


                //event listeners
                $(`${CONTAINER_CLASS} > .left`).click(function (e) {
                    $(this).siblings(SLIDER_CLASS).find(`> .${TAB_ON_CLASS}`).slick('slickPrev');
                });
                $(`${CONTAINER_CLASS} > .right`).click(function (e) {
                    $(this).siblings(SLIDER_CLASS).find(`> .${TAB_ON_CLASS}`).slick('slickNext');
                });

                let onResizeTimer = null;

                //dynamic slider
                $(window).on('resize orientationChange', function (e) {
                    if (onResizeTimer !== null) {
                        clearTimeout(onResizeTimer)
                    }
                    onResizeTimer = setTimeout(() => {
                        //slider dots
                        $(SLIDER_CLASS).each(function () {
                            const dots = $(this).find('.slick-dots > li').children().length
                            if (dots === 0) {
                                $(SLICK_TAB_ARROW_CLASS).addClass('hidden')
                            } else {
                                $(SLICK_TAB_ARROW_CLASS).removeClass('hidden')
                                $(this).find('.slick-dots')
                                    .attr('style', `display: grid !important; grid-template-columns: repeat(${dots}, 1fr) !important`);
                            }
                        });
                        onResizeTimer = null;
                    },
                        100)
                });

                // string
                $(SELECTOR_TAB_CLASS).on('click', (e) => {
                    e.stopPropagation()
                    if ($(e.target).hasClass(TAB_ON_CLASS)) return;
                    $(`${SLICK_TAB_CLASS}.${TAB_ON_CLASS}`).slick('unslick');
                    $(e.target).siblings(SLIDER_TAB_CLASS).removeClass(TAB_ON_CLASS)
                    $(e.target).addClass(TAB_ON_CLASS);
                    $(e.target).parent(SLIDER_CONTAINER_CLASS).siblings(SLICK_TAB_CLASS).removeClass(TAB_ON_CLASS);
                    $(`#${TAB_ID_PREFIX}${e.target.dataset.index}`).addClass(TAB_ON_CLASS);

                    //choose relevant one for sitecore
                    bootstrapSlick()

                })

                $(window).on('load', function (e) {

                    const activeSlickSelector = `${CONTAINER_CLASS} ${SLICK_TAB_CLASS}.${TAB_ON_CLASS}`

                    $(document).find(activeSlickSelector).each(function () {
                        const dots = $(this).find('.slick-dots > li').children().length
                        console.log(dots)
                        if (dots === 0) {
                            $(this).parent(SLIDER_CLASS).siblings(SLICK_TAB_ARROW_CLASS).addClass('hidden')
                        } else {
                            $(this).parent(SLIDER_CLASS).siblings(SLICK_TAB_ARROW_CLASS).removeClass('hidden')
                            $(this).find('.slick-dots')
                                .attr('style', `display: grid !important; grid-template-columns: repeat(${dots}, 1fr) !important`);
                        }
                    })

                });
            },
            initiateStickyNavigation: function () {
                hoverTimer = null;
                var hmcb_nv10 = $('.hmcb-nv10').first();
                var hmcb_nv10b = $('.hmcb-nv10b').first();

                //confirm we have a stickynav
                if (hmcb_nv10 == undefined || hmcb_nv10.length == 0) {
                    return;
                }

                configureScrollLinks = function () {
                    var scroll_links = $(hmcb_nv10).find('.scroll-links')
                    if (scroll_links !== undefined && scroll_links.length > 0) {
                        if ($(hmcb_nv10).find('.scroll-links')[0].scrollWidth > $(hmcb_nv10).find('.scroll-links')[0].clientWidth) {
                            $(hmcb_nv10).find('.scroll-left').addClass('scroll-required')
                            $(hmcb_nv10).find('.scroll-right').addClass('scroll-required')
                        }
                        else {
                            $(hmcb_nv10).find('.scroll-left').removeClass('scroll-required').removeClass('scroll-enabled')
                            $(hmcb_nv10).find('.scroll-right').removeClass('scroll-required').removeClass('scroll-enabled')
                        }
                    }

                    //Move the sub-nav if its too close to the edge of the window
                    var context_menu = $(hmcb_nv10).find('.context-breadcrumb').first();
                    var rect = context_menu[0].getBoundingClientRect()
                    if (window.innerWidth - rect.right < 170) {
                        $(context_menu).find('.sub-nav').attr('style', 'left:-170px')
                    }
                    else {
                        $(context_menu).find('.sub-nav').attr('style', 'left:-8px')
                    }
                }
                updateActiveDecoraton = function () {
                    //remove highlight from all elements
                    var active_links = $('.scroll-links div.active').removeClass("active")
                    var stickyHeight = $(hmcb_nv10).height();

                    var scrollPosition = $(window).scrollTop();
                    var scrollLinks = $(hmcb_nv10).find('.scroll-links >div >a')
                    var activeElement = null;
                    if (scrollLinks !== undefined && scrollLinks.length > 0) {
                        scrollLinks.each((index, element) => {
                            var target = $(element).attr('data-target-element')
                            var targetElement = $(`#${target}`).first();
                            if (targetElement.length === 0) return;

                            var top = Math.max(targetElement.position().top, targetElement.offset().top)
                            if ((top) <= scrollPosition + stickyHeight + (0.5 * stickyHeight)) {
                                activeElement = element;
                            }
                        })
                    }
                    if (activeElement !== null) {
                        $(activeElement).parent().addClass("active")
                    }
                    else {
                        $(hmcb_nv10).find('.scroll-links >div').first().addClass('active')
                    }
                }
                updateScrollArrows = function () {
                    var scrollLinks = $(hmcb_nv10).find('.scroll-links')[0];
                    var maxScrollLeft = scrollLinks.scrollWidth - scrollLinks.clientWidth;
                    if ($(hmcb_nv10).find('.scroll-links')[0].scrollLeft === 0) {
                        $(hmcb_nv10).find('.scroll-left').removeClass('scroll-enabled')
                        $(hmcb_nv10).find('.scroll-right').addClass('scroll-enabled')
                    }
                    else if (Math.trunc($(hmcb_nv10).find('.scroll-links')[0].scrollLeft) >= (maxScrollLeft - 1)) {
                        $(hmcb_nv10).find('.scroll-left').addClass('scroll-enabled')
                        $(hmcb_nv10).find('.scroll-right').removeClass('scroll-enabled')
                    }
                    else {
                        $(hmcb_nv10).find('.scroll-left').addClass('scroll-enabled')
                        $(hmcb_nv10).find('.scroll-right').addClass('scroll-enabled')
                    }
                }
                ShowHideStickyFooter = function () {
                    //shortcut to show/hide sticky footer based on main sticky being shown or not.
                    //requires no changes to 'sticky-nav.js' as this may be used elsewhere.... or not...
                    setTimeout(() => {
                        if ($(hmcb_nv10).hasClass('sticky--fixed')) {
                            $(hmcb_nv10b).addClass('active')
                        }
                        else {
                            $(hmcb_nv10b).removeClass('active')
                        }
                    }, 200);
                }

                $(hmcb_nv10).find('.scroll-to-element').on("click", function (event) {
                    event.preventDefault();
                    var targetElementString = $(this).attr("data-target-element");
                    var targetElement = $('#' + targetElementString);
                    if (targetElement == undefined || targetElement.length == 0) { return; } //Target Element does not exist.

                    var stickyHeight = $(hmcb_nv10).height();
                    var offset = 0;

                    var StickyPosition = parseInt($(hmcb_nv10).attr('data-top')) + 72;
                    var WindowPosition = $(window).scrollTop();
                    var newScrollPosition = $(targetElement).offset().top;

                    const startLocationAboveSticky = (WindowPosition <= StickyPosition);
                    const endLocationAboveSticky = (newScrollPosition <= StickyPosition);

                    if ((startLocationAboveSticky && endLocationAboveSticky) ||
                        (!startLocationAboveSticky && !endLocationAboveSticky)) {
                        //scroll above sticky or scroll below sticky
                        offset = stickyHeight;
                    } else if (startLocationAboveSticky && !endLocationAboveSticky) {
                        //scroll passing over sticky going down
                        offset = stickyHeight * 2;
                    } else if (!startLocationAboveSticky && endLocationAboveSticky) {
                        //scroll passing over sticky going up
                        offset = 0;
                    }
                    window.scrollTo({ top: newScrollPosition - offset, behavior: 'smooth' });
                });
                $(hmcb_nv10).find('.page-heading').on("click", function (event) {
                    event.preventDefault();
                    window.scrollTo({ top: 0, behavior: 'smooth' });
                });
                $(hmcb_nv10).find('.scroll-left').on('click', function (event) {
                    var scrollLinks = $(hmcb_nv10).find('.scroll-links')[0];
                    scrollLinks.scrollLeft -= (50);
                    event.preventDefault();
                    updateScrollArrows();

                })
                $(hmcb_nv10).find('.scroll-right').on('click', function (event) {
                    var scrollLinks = $(hmcb_nv10).find('.scroll-links')[0];
                    scrollLinks.scrollLeft += (50);
                    event.preventDefault();
                    updateScrollArrows();
                })
                $(hmcb_nv10).find('.context-breadcrumb').hover(function (event) {
                    elementHover = this;
                    if (event.type === "mouseenter") {
                        clearTimeout(hoverTimer);
                        hoverTimer = null;
                        $(elementHover).addClass('active')
                        return;
                    }
                    if (event.type === "mouseleave") {
                        hoverTimer = setTimeout(function () {
                            $(elementHover).removeClass('active')
                            hoverTimer = null;
                        }, 200)
                    }
                })
                $(hmcb_nv10).find('.sub-nav').hover(function (event) {
                    if (event.type === "mouseenter") {
                        if (hoverTimer !== null) {
                            clearTimeout(hoverTimer)
                            hoverTimer = null;
                        }
                        $(this).parents('.context-breadcrumb').addClass('active')
                        return;
                    }
                })

                window.setTimeout(configureScrollLinks, 200);

                window.addEventListener('resize', $.throttle(280, () => { configureScrollLinks() }), true);
                window.addEventListener('scroll', () => {
                    updateActiveDecoraton()
                    updateScrollArrows()
                    ShowHideStickyFooter()
                }, true);
            },
            initiateNv05: function () {

                var nv05 = $('.nv05').first();

                if (nv05 === undefined || nv05.length === 0) {
                    return;
                }

                //if ($J('.scroll-to-element') != undefined && $J('.scroll-to-element').length > 0) {

                    $(nv05).find('.scroll-to-element').on("click", function (event) {
                        event.preventDefault();
                        var targetId = $J(this).attr("data-target-element");
                        if (targetId != undefined && $J("#" + targetId).length > 0) {
                            var fixTopNumber = $J('.sticknav').length > 0 && $J("#" + targetId).offset().top >= $('.sticknav').offset().top ? 140 : 70;

                            $('html, body').animate({
                                scrollTop: $J("#" + targetId).offset().top - fixTopNumber
                            }, 1000);
                        }
                    });

                    if (canonHelper.getQueryString("hatch") === 'true' && $J('.nv10 .btn--2.scroll-to-element').length > 0) {
                        $J('.nv10 .btn--2.scroll-to-element').trigger("click");
                    }

                //}
            },
            initComparePage: function () {
                var cb64_compare_results = $(".cb64-compare-results").first();
                if (cb64_compare_results.length == 0) return; 
                //javascript for individual spec sections
                $('.cb68-heading').on('click', function (e) {
                    const sibling = $(this).siblings(".cb68-content")
                    const siblingIsClosed = $(sibling).hasClass('closed')
                    if (siblingIsClosed) {
                        // expand the panel
                        $(sibling).slideDown();
                        $(sibling).removeClass('closed');
                        $(this).removeClass('closed');
                    } else {
                        $(sibling).slideUp().promise().done(() => {
                            $(sibling).addClass('closed');
                            $(this).addClass('closed');
                        })
                    }
                });
                //javascript for expand and collapse ALL content
                $('.cb66-toggle, .cb72-toggle').on('click', function (e) {

                    const EXPAND_TEXT = 'Expand all'
                    const MINIMISE_TEXT = 'Collapse all'

                    const specContainers = $(".cb68-content")
                    const specHeadings = $('.cb68-heading')
                    const innerDiv = $(this).children('div:first').children('span:first');

                    //defaults to expanded, if it has class expanded assume expanded
                    if ($(this).hasClass('expand') && innerDiv.text() === EXPAND_TEXT) {
                        // expand the panels
                        specContainers.slideDown();
                        specContainers.removeClass('closed');
                        specHeadings.removeClass('closed');

                        $('.cb66-toggle').removeClass('expand');
                        $('.cb72-toggle').removeClass('expand');

                        $('.cb66-toggle').children('div:first').children('span:first').text(MINIMISE_TEXT)
                        $('.cb72-toggle').children('div:first').children('span:first').text(MINIMISE_TEXT)

                    } else {
                        specContainers.slideUp().promise().done(() => {
                            specContainers.addClass('closed');
                            specHeadings.addClass('closed');

                            $('.cb66-toggle').addClass('expand');
                            $('.cb72-toggle').addClass('expand');

                            $('.cb66-toggle').children('div:first').children('span:first').text(EXPAND_TEXT)
                            $('.cb72-toggle').children('div:first').children('span:first').text(EXPAND_TEXT)
                        })
                    }
                });

                //tick on checkbox parent to activate radio click for child
                $('.cb66-highlight, .cb72-highlight').on('click', function (e) {
                    const checkboxChild = $(this).find('.fe02-check');
                    const HIGHLIGHTABLE_CLASS = '.cb68-highlightable'
                    const HIGHLIGHT_CLASS = 'cb68-highlight'
                    const PARENT_CLASS = '.cb64-compare-results'
                    const inverseCheck = !checkboxChild.prop("checked")

                    checkboxChild.prop("checked", inverseCheck).promise().done(() => {

                        //convert cb68-highlightable's to cb68-highlight under the parent
                        if (inverseCheck === true) {
                            $(`${PARENT_CLASS} ${HIGHLIGHTABLE_CLASS}`).addClass(HIGHLIGHT_CLASS)
                        } else {
                            $(`${PARENT_CLASS} ${HIGHLIGHTABLE_CLASS}`).removeClass(HIGHLIGHT_CLASS)
                        }

                        $('.cb66-highlight').find('.fe02-check').prop("checked", inverseCheck)
                        $('.cb72-highlight').find('.fe02-check').prop("checked", inverseCheck)
                    });

                });

                //sync scroll between product tile and copy tiles
                const divs = document.querySelectorAll('div.cb66-product-tiles, div.cb68-content');
                divs.forEach(div => div.addEventListener('scroll', e => {
                    divs.forEach(d => {
                        d.scrollRight = div.scrollRight;
                        d.scrollLeft = div.scrollLeft;
                    });
                }));

                //add sticky nav components when
                const stickyClass = '.cb72-compare-block-mini-sticky'
                const compareBlock = '.cb66-compare-block'
                const compareContainer = '.cb64-compare-results'
                const cb65CompareTitleBar = '.cb65-compare-title-bar'
                const globalHeaderSelector = '.sticknav'
                const stickyElement = $(stickyClass);

                const compareContainerHeight = $(compareBlock).height() + $(cb65CompareTitleBar).height() + $(globalHeaderSelector).height();

                $(window).on("scroll", function () {
                    const scroll = $(window).scrollTop();
                    if (scroll > compareContainerHeight && stickyElement.css('display') === 'none') {
                        stickyElement.slideDown()
                    }
                    if (scroll <= compareContainerHeight && stickyElement.css('display') === 'block') {
                        stickyElement.slideUp()
                    }
                });

                //on hover
                const CB68_TOOLTIP_SELECTOR = '.cb68-content-row-heading.cb68-tooltip > .info-hover, .cb68-heading-content.cb68-tooltip > .info-hover';
                const HOVERING_CLASS = 'hovering'
                const ON_HOVER_SELECTOR = '.on-hover'
                let hoverTimer = null;
                $(CB68_TOOLTIP_SELECTOR).hover(function (event) {
                    elementHover = this;
                    if (event.type === "mouseenter") {
                        clearTimeout(hoverTimer);
                        hoverTimer = null;
                        $(CB68_TOOLTIP_SELECTOR).find(ON_HOVER_SELECTOR).removeClass(HOVERING_CLASS)
                        $(this).find(ON_HOVER_SELECTOR).addClass(HOVERING_CLASS)
                        return;
                    }
                    if (event.type === "mouseleave") {
                        hoverTimer = setTimeout(function () {
                            $(elementHover).find(ON_HOVER_SELECTOR).removeClass(HOVERING_CLASS)
                            hoverTimer = null;
                        }, 200)
                    }
                })
                $(".cb64-compare-results").find(ON_HOVER_SELECTOR).hover(function (event) {
                    if (event.type === "mouseenter") {
                        if (hoverTimer !== null) {
                            clearTimeout(hoverTimer)
                            hoverTimer = null;
                        }
                        $(this).find(ON_HOVER_SELECTOR).addClass(HOVERING_CLASS)
                        return;
                    }
                })

                //Add & Remove compare items
                var sessionStorageKey = $(cb64_compare_results).attr("data-compare");
                const sessionStorageChanged = new Event('SessionStorageChanged')
                const BucketValid = isBucketValid(sessionStorageKey)
                $(cb64_compare_results).find(".remove-block").on("click", function (event) {
                    var sitecoreID = $(event.target).parents(".cb66a-wrapper").attr("data-sitecore-item-id");
                    removeCompare(sitecoreID)
                });
                $(stickyClass).find(".remove-block").on("click", function (event) {
                    var sitecoreID = $(event.target).parents(".cb66a-wrapper").attr("data-sitecore-item-id");
                    removeCompare(sitecoreID)
                });
                $(cb64_compare_results).find(".compareCheckbox").on("click", function (event) {
                    var element = $(event.target).parents(".cb70-suggested-product");
                    var sitecoreItemId = $(element).attr('data-sitecore-item-id');
                    var Heading = $(element).find('.cb70-heading').text().trim();
                    var HeadingImageUrl = $(element).find('.cb70-img').css('background-image').replace('url("', "").replace('")', "");
                    //var Url = $(element).find('.secondary >a').attr('href')
                    var Url = "";//todo fix this
                    var product = { sitecoreItemId, Heading, HeadingImageUrl, Url }
                    addCompare(product);

                })
                $(cb64_compare_results).find(".cb65-clear-all").on("click", function () {
                    if (BucketValid) {
                        setStorage(null)
                    }
                    var backLocation = $(cb64_compare_results).find(".cb65-back").attr('href');
                    if (backLocation !== undefined && backLocation !== null && backLocation !== "") {
                        window.location.href = backLocation;
                        return
                    }
                    window.location.href = "/products"
                })

                function addCompare(product) {
                    if (window.location.href.split('?')[1] === undefined) {
                        return;
                    }
                    if (BucketValid) {
                        let data = getStorage();
                        if (data.length > 3) return; //attempting to add a 4th item.
                        data.push(product);
                        setStorage(data);
                    }

                    var searchParams = new URLSearchParams(window.location.href.split('?')[1]);
                    var product1 = searchParams.get("1");
                    var product2 = searchParams.get("2");
                    var from = searchParams.get("from");
                    var Url = `/compare?1=${product1}&2=${product2}&3=${product.sitecoreItemId}`
                    if (from !== null) {
                        Url += `&from=${from}`;
                    }
                    window.location.href = Url;
                }
                function removeCompare(productID) {
                    if (window.location.href.split('?')[1] === undefined) {
                        return;
                    }
                    if (BucketValid) {
                        let data = getStorage();
                        for (let index = 0; index < data.length; index++) {
                            const element = data[index];
                            if (element.sitecoreItemId === productID) {
                                //remove item
                                data.splice(index, 1);
                                setStorage(data);
                            }
                        }
                    }

                    var searchParams = new URLSearchParams(window.location.href.split('?')[1]);
                    var product1 = searchParams.get("1");
                    var product2 = searchParams.get("2");
                    var product3 = searchParams.get("3");
                    var from = searchParams.get("from");

                    if (product1 !== null && product1 === productID) {
                        //removing product 1
                        product1 = null;
                    }
                    if (product2 !== null && product2 === productID) {
                        //removing product 2
                        product2 = null;
                    }
                    if (product3 !== null && product3 === productID) {
                        //removing product 3
                        product3 = null;
                    }

                    //confirm we still have at least 2 products for compare.
                    if ((product1 === null && product2 === null) || (product1 === null && product3 === null) || (product2 === null && product3 === null)) {
                        //we no longer have 2 compare products. Send user back to original page.
                        alert("You require at least 2 items to compare");
                        var backUrl = $(cb64_compare_results).find(".cb65-back").attr("href")
                        window.location.href = backUrl;
                        return;
                    }
                    var Url = "/compare?";
                    index = 1;
                    if (product1 !== null) {
                        Url += `${index}=${product1}&`;
                        index++
                    }
                    if (product2 !== null) {
                        Url += `${index}=${product2}&`;
                        index++
                    }
                    if (product3 !== null) {
                        Url += `${index}=${product3}&`;
                    }
                    if (from !== null) {
                        Url += `from=${from}`;
                    }

                    

                    window.location.href = Url;
                }
                function getStorage() {
                    let storage = sessionStorage.getItem(sessionStorageKey)
                    if (storage !== null) {
                        return JSON.parse(storage)
                    }
                    return [];
                }
                function setStorage(object) {
                    if (object === null) {
                        sessionStorage.removeItem(sessionStorageKey)
                    }
                    else {
                        sessionStorage.setItem(sessionStorageKey, JSON.stringify(object))
                    }
                    window.dispatchEvent(sessionStorageChanged);
                }

                function isBucketValid(bucketName) {
                    var data = getStorage();
                    if (data.length === 0) return false;
                    var products = $(cb64_compare_results).find(".cb66a-wrapper")
                    if (products.length === 0) return false;
                    if (data.length !== products.length) return false;

                    for (let indexProducts = 0; indexProducts < products.length; indexProducts++) {
                        sitecoreID = $(products[indexProducts]).attr("data-sitecore-item-id");
                        if (sitecoreID === undefined || sitecoreID === null || sitecoreID === "") return false;

                        found = false;
                        for (let indexData = 0; indexData < data.length; indexData++) {
                            if (data[indexData].sitecoreItemId === sitecoreID) {
                                found = true;
                            }
                        }
                        if (!found) return false;
                    }
                    return true;
                };

                //remove suggested products
                $(cb64_compare_results).find(".cb70-close").on("click", function (event) {
                    console.log($(event.target).parents(".cb70-suggested-product"));
                    $(event.target).parents(".cb70-suggested-product").remove();

                    var remainingSuggestions = $(cb64_compare_results).find(".cb70-suggested-product");
                    if (remainingSuggestions.length === 0) {
                        $(cb64_compare_results).find(".cb69-suggested-container").remove()
                    }
                });

                //print & email
                //window.print();
                $(cb64_compare_results).find(".cb66-print").on("click", function () {
                    //fetch page HTML
                    var page = $(".cb64-compare-results").first().prop("outerHTML");
                    //create new object from HTML
                    var page2 = $(page)
                    //remove stuff
                    $(page2).find(".cb65-compare-title-bar").remove()
                    $(page2).find(".compare-results-sidebar").remove()
                    $(page2).find(".cb66-icons").remove()
                    $(page2).find(".cb66-toggles").remove()
                    $(page2).find(".remove-block").remove()
                    $(page2).find(".img-container").each(function (index, item) {
                        $(item).css('content', $(item).css('background-image'));
                    });
                    //send the new HTML to the print popup
                    PrintElem(page2.prop("outerHTML"))
                })
                $(cb64_compare_results).find(".cb66-email").on("click", function () {
                    SendLinkByMail();
                })
                $(".cb72-compare-block-mini-sticky").find(".cb72-print").on("click", function () {
                    //fetch page HTML
                    var page = $(".cb64-compare-results").first().prop("outerHTML");
                    //create new object from HTML
                    var page2 = $(page)
                    //remove stuff
                    $(page2).find(".cb65-compare-title-bar").remove()
                    $(page2).find(".compare-results-sidebar").remove()
                    $(page2).find(".cb66-icons").remove()
                    $(page2).find(".cb66-toggles").remove()
                    $(page2).find(".remove-block").remove()
                    $(page2).find(".img-container").each(function (index, item) {
                        $(item).css('content', $(item).css('background-image'));
                    });
                    //send the new HTML to the print popup
                    PrintElem(page2.prop("outerHTML"))
                })
                $(".cb72-compare-block-mini-sticky").find(".cb72-email").on("click", function () {
                    SendLinkByMail();
                })
                function PrintElem(elem) {
                    var mywindow = window.open('', 'PRINT');

                    mywindow.document.write('<html><head><title>' + document.title + '</title>');
                    mywindow.document.write('<link href="/css/canon-common.min.css" rel="stylesheet">');
                    mywindow.document.write('</head><body >');
                    mywindow.document.write(elem);
                    mywindow.document.write('</body></html>');

                    setTimeout(function () {
                        $(mywindow.document).ready(function () {
                            console.log("bla2");
                            mywindow.print();
                            mywindow.close();
                        })
                        return true;
                    }, 100)
                    
                    return true;
                }
                function SendLinkByMail() {
                    var subject = "Sharing with you my selection of Canon products";
                    var body = "Sharing with you my selection of Canon products\r\n\r\nI’ve narrowed down my selection of Canon gear to two or three options, you can compare the differences and download the product brochures.\r\n\r\nPlease follow the link to see my selection:";
                    body += window.location.href;
                    var uri = "mailto:?subject=";
                    uri += encodeURIComponent(subject);
                    uri += "&body=";
                    uri += encodeURIComponent(body);
                    window.open(uri);
                }
            },
            initiateProductTile: function () {
                var sessionStorageKey = $('.cb58').first().attr('data-compare');
                const sessionStorageChanged = new Event('SessionStorageChanged')
                $(window).on('SessionStorageChanged', () => {
                    //read current session storage object and update component
                    refreshComponent()
                })

                const cb58ItemsChanged = new Event('cb58ItemsChanged')
                $(window).on('cb58ItemsChanged', () => {
                    //reconfigure on change event
                    sessionStorageKey = $('.cb58').first().attr('data-compare');
                    $('.cb58').find('.compareCheckbox').on('change', CompareCheckboxChanged)
                    refreshComponent()
                })

                refreshComponent()
                function refreshComponent() {
                    let data = getStorage();

                    //untick everything
                    $(".cb58").find('.compareCheckbox').prop('checked', false).parent().removeClass('active');
                    if (data.length === 0) {
                        return;
                    }

                    data.forEach(product => {
                        element = $(".cb58[data-sitecore-item-id='" + product.sitecoreItemId + "']").find('.compareCheckbox');
                        $(element).prop('checked', true)

                        //update compare with selected class, to darken the background color
                        $(element).parent().addClass('active')
                    });
                }

                $('.cb58').find('.compareCheckbox').on('change', CompareCheckboxChanged)

                function CompareCheckboxChanged(event) {
                    var element = $(event.target).parents('.cb58');
                    var sitecoreItemId = $(element).attr('data-sitecore-item-id');
                    var Heading = $(element).find('.product-info >.title').text().replace(/(\r\n|\n|\r)/gm, "").trim();
                    var HeadingImageUrl = $(element).find('.img-container').css('background-image').replace('url("', "").replace('")', "");
                    var Url = $(element).find('.secondary >a').attr('href')
                    var product = { sitecoreItemId, Heading, HeadingImageUrl, Url }

                    if (event.target.checked) {
                        if (!addCompare(product)) {
                            //trigger error popup
                            $(event.target).parents('.actions').prepend('<div class="max-compare"><span>You can only compare up to 3 items.</span></div>')
                            setTimeout(() => {
                                $(event.target).parents('.actions').find('.max-compare').addClass('show')
                                setTimeout(() => {
                                    $(event.target).parents('.actions').find('.max-compare').removeClass('show')
                                    setTimeout(() => {
                                        $(event.target).parents('.actions').find('.max-compare').remove()
                                    }, 500);
                                }, 5000);
                            });

                            //unselect input
                            $(event.target).prop('checked', false)
                        }
                        else {
                            //update compare with selected class, to darken the background color
                            $(event.target).parent().addClass('active')
                        }
                    }
                    else {
                        removeCompare(sitecoreItemId)
                        $(event.target).parent().removeClass('active')
                    }
                }

                function addCompare(product) {
                    let data = getStorage(sessionStorageKey);
                    if (data.length >= 3) {
                        console.error("You can only compare up to 3 items.")
                        //trigger error popup
                        return false;
                    }

                    for (let index = 0; index < data.length; index++) {
                        const element = data[index];
                        if (element.sitecoreItemId === product.sitecoreItemId) {
                            //item already added
                            return true;
                        }
                    }

                    data.push(product);
                    setStorage(data, sessionStorageKey);
                    return true;
                }
                function removeCompare(sitecoreItemId) {
                    let data = getStorage(sessionStorageKey);
                    for (let index = 0; index < data.length; index++) {
                        const element = data[index];
                        if (element.sitecoreItemId === sitecoreItemId) {
                            //remove item
                            data.splice(index, 1);
                            return setStorage(data, sessionStorageKey);
                        }
                    }
                    return false;
                }
                function getStorage() {
                    let storage = sessionStorage.getItem(sessionStorageKey)
                    if (storage !== null) {
                        return JSON.parse(storage)
                    }
                    return [];
                }
                function setStorage(object) {
                    if (object === null) {
                        sessionStorage.removeItem(sessionStorageKey)
                    }
                    else {
                        sessionStorage.setItem(sessionStorageKey, JSON.stringify(object))
                    }
                    window.dispatchEvent(sessionStorageChanged);
                }
            },
            initiateCompareBucket: function () {
                const cb62 = $('.cb62').first();
                //on page load, read session storage for any selected compare
                const sessionStorageKey = $(cb62).attr('data-compare')
                refreshComponent()

                //setup custom event
                const sessionStorageChanged = new Event('SessionStorageChanged')
                $(window).on('SessionStorageChanged', () => {
                    //read current session storage object and update component
                    refreshComponent()
                })

                $(cb62).find('.clear-all').on('click', function (event) {
                    clearComponent();
                })
                $(cb62).find('.compare-now').on('click', function (event) {
                    var fromId = $(cb62).attr("data-from");
                    let data = getStorage();
                    if (data.length <= 1) {
                        console.error("Require at least 2 items to compare")
                        return;
                    }

                    let queryString = "";
                    for (let index = 0; index < data.length; index++) {
                        const element = data[index];
                        queryString += `${index + 1}=${element.sitecoreItemId}&`;
                    }
                    if (fromId !== undefined && fromId !== null && fromId !== "") {
                        queryString += `from=${fromId}&`
                    }
                    window.location.href = `/compare?${queryString.slice(0, -1)}` 
                })


                function refreshComponent() {
                    let data = getStorage();
                    $(cb62).find('.product').removeAttr('data-sitecore-item-id').empty();
                    $(cb62).find('.compare-now').attr('disabled', 'disabled')
                    if (data.length === 0) {
                        $(cb62).addClass('hidden');
                        return;
                    }

                    var template = $('#cb62-product').html();
                    for (let index = 0; index < data.length; index++) {
                        const element = data[index];

                        var result = Mustache.to_html(template, element);
                        $(cb62).find('.product').eq(index).attr('data-sitecore-item-id', element.sitecoreItemId).append(result);

                    }
                    $(cb62).find('.remove-compare').on('click', function (event) {
                        let parent = $(event.target).parents('.product');
                        let sitecoreItemId = $(parent).attr('data-sitecore-item-id');
                        removeCompare(sitecoreItemId);
                    })
                    if (data.length >= 2) {
                        $(cb62).find('.compare-now').removeAttr('disabled')
                    }
                    $(cb62).removeClass('hidden');
                }
                function clearComponent() {
                    setStorage(null)
                }
                function addCompare(product) {
                    let data = getStorage();
                    if (data.length >= 3) {
                        console.error("You can only compare up to 3 items.")
                        //trigger error popup
                        return false;
                    }

                    for (let index = 0; index < data.length; index++) {
                        const element = data[index];
                        if (element.sitecoreItemId === product.sitecoreItemId) {
                            //item already added
                            return true;
                        }
                    }

                    data.push(product);
                    setStorage(data);
                    return true;
                }
                function removeCompare(sitecoreItemId) {
                    let data = getStorage();
                    for (let index = 0; index < data.length; index++) {
                        const element = data[index];
                        if (element.sitecoreItemId === sitecoreItemId) {
                            //remove item
                            data.splice(index, 1);
                            return setStorage(data);
                        }
                    }
                    return false;
                }
                function getStorage() {
                    let storage = sessionStorage.getItem(sessionStorageKey)
                    if (storage !== null) {
                        return JSON.parse(storage)
                    }
                    return [];
                }
                function setStorage(object) {
                    if (object === null) {
                        sessionStorage.removeItem(sessionStorageKey)
                    }
                    else {
                        sessionStorage.setItem(sessionStorageKey, JSON.stringify(object))
                    }
                    window.dispatchEvent(sessionStorageChanged);
                }
            },
            initProductCompatibilityRefiner2: function () {
                var cb59a = $('.cb59a').first();
                var cb59c = $('.cb59c').first();
                var cb59d = $('.cb59d').first();
                var component = null;
                var textInputComponent = null;
                var selectableIndex = 1;
                if (cb59a.length === 0 && cb59c.length === 0 && cb59d.length === 0) { return; }
                if (cb59d.length !== 0) {
                    component = cb59d;
                    textInputComponent = $(component).find("#container-0-label-1").first();
                }
                if (cb59c.length !== 0) { component = cb59c; }
                
                if (cb59a.length !== 0) {
                    component = cb59a;
                    textInputComponent = $(component).find("#container-1-label-1").first();

                    $('.cb59a .compatible-tabs > .tab-container').not(">svg").on('click', (e) => {
                        e.stopPropagation()
                        if ($(e.target).hasClass("active-tab")) return;
                        $('.cb59a .compatible-tabs > .tab-container').removeClass('active-tab')
                        $(e.target).addClass('active-tab');
                        $('.cb59a .selection-container > .filters-container').removeClass('show-filters')
                        $(`#cb59a-filter-container-${e.target.dataset.index}`).addClass('show-filters');
                        $('.cb59a .instructions').removeClass('show-instructions')
                        $(`#cb59a-instructions-${e.target.dataset.index}`).addClass('show-instructions');
                        selectableIndex = e.target.dataset.index;

                        if (selectableIndex == 1) {
                            selectedValue = $(component).find("#ddlModelNumber select").val();
                             if (selectedValue !== undefined && selectedValue !== null && selectedValue !== "") {
                                $(component).find('.show-results').removeAttr('disabled')
                            }
                            else {
                                $(component).find('.show-results').attr('disabled', 'disabled')
                            }
                        }
                        else if (selectableIndex == 2) {
                            searchValue = $(textInputComponent).val();
                            if (searchValue !== undefined && searchValue !== null && searchValue !== "") {
                                $(component).find('.show-results').removeAttr('disabled')
                            }
                            else {
                                $(component).find('.show-results').attr('disabled', 'disabled')
                                return;
                            }
                        }
                    });
                }

                
                var pageFirstLoad = "";
                //setup custom event
                const CompatibilityRefinerChanged = new Event('CompatibilityRefinerChanged')
                const CompatibilityRefinerStartAgain = new Event('CompatibilityRefinerStartAgain')

                $(component).find('#ddlModelName select').change(function (e) {
                    $(component).find('.show-results').attr('disabled', 'disabled')
                    var selectedItem = $(this).find('option:selected').text().trim()
                    if (selectedItem === undefined || selectedItem === null || selectedItem === "") {
                        var select = $(component).find("#ddlModelNumber select");
                        select.empty().append('<option value="">Select</option>')
                        return;
                    }
                    var dataSourceId = $(component).attr('data-source-id');
                    $.post('/content-tile/productfeed/getcompatiblemodels', { "seriesName": selectedItem, "dataSourceId": dataSourceId })
                        .then(function (response) {
                            var select = $(component).find("#ddlModelNumber select");
                            select.empty().append('<option value="">Select</option>')
                            response.forEach(function (item) {
                                select.append('<option value="' + item + '">' + item + '</option>')
                                if (pageFirstLoad !== "") {
                                    $(component).find("#ddlModelNumber select").val(decodeURI(pageFirstLoad))
                                    pageFirstLoad = "";
                                    $(component).find("#ddlModelNumber select").change();
                                }
                            })
                        });
                });
                $(component).find("#ddlModelNumber select").change(function (e) {
                    selectedValue = $(component).find("#ddlModelNumber select").val();
                    if (selectedValue !== undefined && selectedValue !== null && selectedValue !== "") {
                        $(component).find('.show-results').removeAttr('disabled')
                    }
                    else {
                        $(component).find('.show-results').attr('disabled', 'disabled')
                    }
                })
                $(component).find(".show-results").on("click", showResults);
                $(component).find(".start-again").on("click", function (event) {
                    var basePage = window.location.href.split('?')[0];
                    
                    history.replaceState(null, null, basePage)
                    $(component).find('#ddlModelName select').val("");
                    $(component).find("#ddlModelNumber select").val("")
                    $(component).find('.show-results').attr('disabled', 'disabled')
                    $(textInputComponent).val("")
                    window.dispatchEvent(CompatibilityRefinerStartAgain);
                });
                $(textInputComponent).on("keyup", function (event) {
                    searchValue = event.currentTarget.value;
                    if (searchValue !== undefined && searchValue !== null && searchValue !== "") {
                        $(component).find('.show-results').removeAttr('disabled')
                    }
                    else {
                        $(component).find('.show-results').attr('disabled', 'disabled')
                        return;
                    }
                })
                $(textInputComponent).on("keydown", function (event) {
                    if (event.keyCode === 13) {
                        showResults();
                    }
                })
                function showResults() {
                    var basePage = window.location.href.split('?')[0];
                    
                    if ((cb59a.length !== 0 && selectableIndex == 1) ||
                        cb59c.length !== 0) {
                        //dropdown menu, pulling compatible products
                        var series = $(component).find('#ddlModelName select option:selected').val().trim();
                        var model = $(component).find('#ddlModelNumber select option:selected').val().trim();
                        if (series === "" || model === "") return;

                        basePage += `?compatible=${series},${model}`;
                    }
                    else if ((cb59a.length !== 0 && selectableIndex == 2) ||
                        cb59d.length !== 0) {
                        //searchable field for productfeed
                        searchValue = $(textInputComponent).val();
                        if (searchValue === "") return;

                        basePage += `?search=${searchValue}`;
                    }
                    history.replaceState(null, null, basePage)
                    window.dispatchEvent(CompatibilityRefinerChanged);
                    var scrollLocation = $(component).find('.selection-container').first();
                    scrollLocation[0].scrollIntoView({
                        behavior: "smooth",
                        block: "start"
                    });
                    $(textInputComponent).blur();

                }
                function OnPageFirstLoad() {
                    var Query = window.location.href.split('?')[1];
                    if (Query !== undefined && Query !== "") {
                        Query.split('&').forEach(section => {
                            var key = section.split('=')[0]
                            var values = section.split('=')[1].split(',')
                            if (key == 'compatible' && values.length >= 2) {
                                pageFirstLoad = decodeURI(values[1]);
                                $('#ddlModelName select').val(decodeURI(values[0])).change();
                            }
                            if (key == 'search' && values.length >= 1) {
                                $(textInputComponent).val(decodeURI(values[0]));
                            }
                        });
                    }

                    if (cb59a.length !== 0) {
                        //get selectable index
                        var selectedId = $(cb59a).find('.filters-container.show-filters').first().attr('id');
                        if (selectedId === "cb59a-filter-container-2") {
                            selectableIndex = 2
                        }
                    }
                }
                OnPageFirstLoad()
            },
            initiateProductTileFilter: function () {
                var hoverTimer = null;
                var element_cb61 = $('.cb61').first();
                var element_cb61b = $('.cb61b').first();
                var element_cf13 = $(element_cb61b).parent().find('.cf13').first();
                var element_sort = '#cb61-sort-select';
                if (element_cb61.length == 0) return;

                if (!window.location.href.includes("sc_itemid")) {
                    $('body').css('overflow', 'auto'); //fixes bug where page scrolls to top after opening mobile filters
                    $('html').css('overflow', 'hidden'); //fixes bug from above line that causes 2 vertical scroll bars on this page
                }
                var basePage = updateBasePage();

                //setup custom event
                const CompatibilityRefinerChanged = new Event('CompatibilityRefinerChanged')
                const CompatibilityRefinerStartAgain = new Event('CompatibilityRefinerStartAgain')
                $(window).on('CompatibilityRefinerChanged', () => {
                    basePage = updateBasePage();
                    updateCheckboxesFromQueryString(true, true, true);
                })
                $(window).on('CompatibilityRefinerStartAgain', () => {
                    basePage = updateBasePage();
                    $(element_cb61b).find(element_sort).prop("selectedIndex", 0).trigger('change', 'false')//should be "Featured"
                    clearActiveFilters(true)
                })

                //workaround for layout--color having overflow: hidden
                //this overflow setting will prevent position: sticky from working
                $(element_cb61).parents('.layout--color').css('overflow', 'unset');
                $(window).resize(function () {
                    //fixes bug where page can be no scrollable after changing window size when filter is open
                    if (window.matchMedia('(max-width: 768px)').matches) {
                        if (!$(element_cb61).hasClass('collapsed')) {
                            $('body').css('overflow', 'hidden');
                            return;
                        }
                    }
                    
                    $('body').css('overflow', 'auto');
                });

                $(element_cb61).find('.filter-heading >.heading').each((index_heading, heading) => {
                    $(heading).on('click', function (event) {
                        $(this).parent().toggleClass("collapsed");
                    })
                })
                $(element_cb61).find(".filter-button, .cancel-button").on('click', function (event) {
                    //resume scrolling main window when mobile overlay is closed
                    $('body').css('overflow', 'auto');

                    $(element_cb61b).removeClass('collapsed');
                    $(element_cb61).addClass('collapsed');
                })
                $(element_cb61).find(".apply-button").on('click', function (event) {
                    //resume scrolling main window when mobile overlay is closed
                    $('body').css('overflow', 'auto');

                    $(element_cb61b).removeClass('collapsed');
                    $(element_cb61).addClass('collapsed');
                })
                $(element_cb61).find('.clearAll').on('click', function (event) {
                    clearActiveFilters(false)

                    if (window.matchMedia('(max-width: 768px)').matches) {
                        //if changing from 768px, also update various CSS @media

                        //close the filter section if in mobile view
                        $(element_cb61b).removeClass('collapsed');
                        $(element_cb61).addClass('collapsed');

                        //resume scrolling main window when mobile overlay is closed
                        $('body').css('overflow', 'auto');
                    }
                })
                $(element_cb61).find('.info-hover').hover(function (event) {
                    elementHover = this;
                    if (event.type === "mouseenter") {
                        clearTimeout(hoverTimer);
                        hoverTimer = null;
                        $(element_cb61).find(".on-hover").removeClass('hovering')
                        $(this).find('.on-hover').addClass('hovering')
                        return;
                    }
                    if (event.type === "mouseleave") {
                        hoverTimer = setTimeout(function () {
                            $(elementHover).find('.on-hover').removeClass('hovering')
                            hoverTimer = null;
                        }, 200)
                    }
                })
                $(element_cb61).find('.on-hover').hover(function (event) {
                    if (event.type === "mouseenter") {
                        if (hoverTimer !== null) {
                            clearTimeout(hoverTimer)
                            hoverTimer = null;
                        }
                        $(this).find('.on-hover').addClass('hovering')
                        return;
                    }
                })
                $(element_cb61).find(".filter-item").on("click", function (event) {
                    if (event.target.type !== 'checkbox') {
                        return;
                    }

                    //call function to evaluate which items are checked, and update URL Hash
                    updateQueryString()
                    var filter_id = $(event.target).parents('.filter-heading').attr('data-filter-id')
                    var filter_text = $(event.target).parents('.filter-item').attr('data-filter-label')
                    var selected = $(event.target).prop("checked")
                    selected ? addActiveFilter(filter_id, filter_text) : removeActiveFilter(filter_id, filter_text)
                    //make request to API for products, and filters count
                    fetchProducts()
                })

                $(element_cb61b).find('.filter-button').on('click', function (event) {
                    $(element_cb61b).addClass('collapsed')
                    $(element_cb61).removeClass('collapsed')

                    if (window.matchMedia('(max-width: 768px)').matches) {
                        //if changing from 768px, also update various CSS @media

                        //prevent scrolling main window when mobile overlay is open
                        $('body').css('overflow', 'hidden');
                    }
                })

                function updateBasePage() {
                    var bp = window.location.href.split('?')[0];
                    if (window.location.href.split('?')[1] !== undefined &&
                        window.location.href.split('?')[1].includes('compatible=')) {
                        bp += "?";
                        var compatibleIndex = window.location.href.split('?')[1].indexOf('compatible=');
                        var nextKey = window.location.href.split('?')[1].indexOf('&', compatibleIndex);

                        bp += nextKey === -1
                            ? window.location.href.split('?')[1].substr(compatibleIndex)
                            : window.location.href.split('?')[1].substr(compatibleIndex, nextKey)

                    }
                    return bp;
                }
                function updateQueryString() {
                    var selectedFilters = {}
                    $(element_cb61).find(".filter-heading").each((index, element) => {
                        selectedFilters[element.dataset.filterId] = [];
                        $(element).find("input[type=checkbox]")
                            .each((index_checkbox, element_checkbox) => {
                                if ($(element_checkbox).prop('checked')) {
                                    var filter_text = $(element_checkbox).parents('.filter-item').attr('data-filter-label')
                                    selectedFilters[element.dataset.filterId].push(filter_text)
                                }
                            })
                    })

                    var hashValue = "";
                    for (let s in selectedFilters) {
                        var values = "";
                        var counter = selectedFilters[s].length;
                        if (selectedFilters[s].length > 0) {
                            for (let v in selectedFilters[s]) {
                                if (counter > 0) {
                                    values += `${selectedFilters[s][v]},`;
                                    counter--;
                                }
                            }
                            hashValue += `${s}=${values.slice(0, -1)}&`;
                        }
                    }

                    var sortValue = $(element_cb61b).find(element_sort).val()
                    if (sortValue !== undefined && sortValue !== "Featured") {
                        hashValue += `sort=${encodeURI(sortValue)}&`;
                    }
                    if (hashValue.slice(0, -1).length == 0) {
                        history.replaceState(null, null, basePage)
                        return;
                    }

                    var newHistory = basePage.includes('compatible')
                        ? basePage + "&" + hashValue.slice(0, -1)
                        : basePage + "?" + hashValue.slice(0, -1)
                    history.replaceState(null, null, newHistory)
                }
                function updateCheckboxesFromQueryString(addPills, updateProducts, refinerChanged) {
                    //unselect all checkboxes
                    $(element_cb61).find("input[type=checkbox]").prop('checked', false);
                    if (refinerChanged) {
                        $(element_cb61b).find('.active-filters .active-filter-primary').remove();
                        $(element_cb61b).find('.active-filters .active-filter').remove()
                        $(element_cf13).attr('data-search', "")
                    }

                    //select boxes based on query string
                    var Query = window.location.href.split('?')[1];
                    if ((Query === undefined || Query.length === 0) && updateProducts) {
                        clearActiveFilters(false)
                        return;
                    }
                    if (Query === undefined || Query.length === 0 || Query.match("sc_itemid")) { return; }
                    Query.split('&').forEach(section => {
                        var key = section.split('=')[0]
                        var values = section.split('=')[1].split(',')
                        if (key == 'compatible' && values.length >= 2) {
                            addPrimaryFilter(values[0], values[1])
                            return;
                        }
                        if (key == 'search' && values.length >= 1) {
                            $(element_cf13).attr('data-search', decodeURI(values[0]))
                            return;
                        }
                        if (key == 'sort' && values.length >= 1 && decodeURI(values[0]) !== 'Featured') {
                            $(element_cb61b).find(element_sort).val(decodeURI(values[0]))
                            setTimeout(() => {
                                console.log("sort: ", $(element_cb61b).find(element_sort).val())
                                if ($(element_cb61b).find(element_sort).val() == null) {
                                    $(element_cb61b).find(element_sort).prop("selectedIndex", 0)//should be "Featured"
                                        .trigger('change');
                                }
                            })
                            return;
                        }
                        values.forEach(value => {
                            if (value === '') {
                                return
                            }
                            var element = $(element_cb61).find("div[data-filter-id='" + decodeURI(key) + "'] div[data-filter-label='" + decodeURI(value) + "'] input[type=checkbox]");
                            if (element.length == 0) { return; }
                            element.prop('checked', true)
                            if (addPills) { addActiveFilter(decodeURI(key), decodeURI(value)); }
                        });
                    });

                    //now load the appropriate products from feed
                    if (updateProducts) { fetchProducts(); }
                }
                function addActiveFilter(key, value) {
                    //pills

                    var existing = $(element_cb61b).find(".active-filter div[data-filter-id='" + key + "'][data-filter-label='" + value + "']")
                    if (existing.length === 0) {
                        //add new element to page
                        $(element_cb61b).find('.active-filters').append(`<div class="active-filter" data-filter-id="${key}" data-filter-label="${value}">${value}</div>`)

                        //setup click event to remove it.
                        $(element_cb61b).find(".active-filters .active-filter[data-filter-id='" + key + "'][data-filter-label='" + value + "']").on('click', function (event) {
                            removeActiveFilter(key, value)
                            updateQueryString();
                            fetchProducts()
                        })
                    }

                    //ensure checkbox is selected
                    $(element_cb61).find(`div[data-filter-id='${key}'] div[data-filter-label='${value}'] input[type=checkbox]`).prop('checked', true)
                }
                function removeActiveFilter(key, value) {
                    //pills
                    var existing = $(element_cb61b).find(".active-filters .active-filter[data-filter-id='" + key + "'][data-filter-label='" + value + "']")
                    if (existing.length > 0) {
                        existing.remove();
                    }

                    //ensure checkbox is unselected
                    $(element_cb61).find("div[data-filter-id='" + key + "'] div[data-filter-label='" + value + "'] input[type=checkbox]").prop('checked', false)
                }
                function clearActiveFilters(clearRefiner) {
                    history.replaceState(null, null, basePage);

                    //remove pills
                    $(element_cb61b).find('.active-filters .active-filter').remove()

                    //unselect checkboxes
                    $(element_cb61).find('input[type=checkbox]').prop('checked', false);

                    //clear existing product list.
                    $(element_cf13).find('> .tile-container').empty();

                    if (clearRefiner) {
                        $(element_cb61b).find('.active-filters .active-filter-primary').remove();
                        $(element_cf13).attr('data-search', "")
                    }

                    fetchProducts()
                }
                function addPrimaryFilter(value1, value2) {
                    var container = $(".cf13-cb61-split-container").first();
                    var selectionType = container.attr("data-selection-type")
                    var selectionFor = container.attr("data-selection-for")

                    $(element_cb61b).find('.active-filters .active-filter-primary').remove();
                    $(element_cb61b).find('.active-filters').prepend(`<div class="active-filter-primary" data-series="${decodeURI(value1)}" data-model="${decodeURI(value2)}">${decodeURI(selectionType)} results for your ${decodeURI(selectionFor)}:&nbsp;<span>${decodeURI(value1)}&nbsp;${decodeURI(value2)}</span></div>`)
                }
                
                function fetchProducts() {
                    //clear existing product list.
                    $(element_cf13).find('> .tile-container').empty();

                    //clear the results count
                    $(element_cb61b).find('.filter-row >span').text("");

                    //used below to discard stale results
                    var filterString = window.location.href.split('?')[1];

                    //SOME FILTERS ARE SELECTED
                    //query=268C22F7-1BA7-4D83-9559-420B690A6001,268C22F7-1BA7-4D83-9559-420B690A6002,268C22F7-1BA7-4D83-9559-420B690A6003
                    var sitecoreQueryString = defaultFunctions.getSitecoreQueryString(element_cb61)
                    // console.log(sitecoreQueryString);
                    //make request to API for products with no filters selected
                    if (sitecoreQueryString !== null) {

                        getProducts(sitecoreQueryString, filterString);
                    }
                    else {
                        getAllProducts(filterString);
                    }
                    return;
                }
                async function getProducts(filterKeys, filterString) {
                    var tileContainer = $J('.cf13').find('.tile-container');
                    var sourceId = $J(tileContainer).attr('data-source');
                    var compatibleSeries = $(element_cb61b).find('.active-filters .active-filter-primary').attr('data-series');
                    var compatibleModel = $(element_cb61b).find('.active-filters .active-filter-primary').attr('data-model');
                    var searchValue = $(element_cf13).attr('data-search');
                    var sortValue = $(element_cb61b).find(element_sort).val();
                    //todo, fix this. I don't like it
                    var CompatibilityRefinerDataSource = $("div[class^='cb59']").first().attr("data-source-id");

                    //unselect the selected dropdown filters
                    if (filterKeys.match("sc_itemid")) { return }
                    var postData = {
                        ProductParentId: sourceId,
                        PageIndex: 0,
                        PageSize: 9,
                        SelectedFilterType: 'productfeedfilter',
                        CompatibleSeries: compatibleSeries,
                        CompatibleModel: compatibleModel,
                        CompatibilityRefinerDataSource: CompatibilityRefinerDataSource,
                        ProductSearch: searchValue,
                        SelectedFilter: filterKeys,
                        IsPartnerRequest: $J(tileContainer).attr('data-isPartnerRequest'),
                        Sort: sortValue !== undefined ? sortValue : 'Featured'
                    };
                    await defaultFunctions.getProductsFeedTiles(postData, tileContainer, false, true, true, filterString);
                }
                async function getAllProducts(filterString) {
                    var tileContainer = $J('.cf13').find('.tile-container');
                    var sourceId = $J(tileContainer).attr('data-source');
                    var sortValue = $(element_cb61b).find(element_sort).val();
                    //unselect the selected dropdown filters

                    var postData = {
                        ProductParentId: sourceId,
                        PageIndex: 0,
                        PageSize: 9,
                        SelectedFilterType: 'productfeedfilter',
                        SelectedFilter: '',
                        IsPartnerRequest: $J(tileContainer).attr('data-isPartnerRequest'),
                        Sort: sortValue !== undefined ? sortValue : 'Featured'
                    };
                    await defaultFunctions.getProductsFeedTiles(postData, tileContainer, false, true, true, filterString);
                }
                function updateFilterCounts(filterCounts) {
                    for (let heading in filterCounts) {
                        var count = filterCounts[heading]
                        var filter_item = $(element_cb61).find("div[data-sitecore-id='" + heading + "']")
                        $(filter_item[0]).find('.count').html('(' + count + ')');
                        if (count == 0) {
                            $(filter_item).addClass('disabled')
                            $(filter_item).find('input').attr('disabled', true)
                        }
                        else {
                            $(filter_item).removeClass('disabled')
                            $(filter_item).find('input').attr('disabled', false)
                        }
                    }
                }
                
                function cf13_addProducts(products) {
                    var template = $('#cb58-template').html(); //REPLACE WITH YOUR FUNCTION TO FETCH YOUR MUSTACHE
                    var result = Mustache.to_html(template, products);
                    $(element_cf13).find('.tile-container').append(result);
                }
                updateCheckboxesFromQueryString(true, true, false);//run on page load or page refresh

                if (window.matchMedia('(max-width: 768px)').matches) {
                    $(element_cb61).addClass('collapsed')
                    $(element_cb61b).removeClass('collapsed')
                }

                const FF05_SELECTOR_NAME = ".ff05-selector"
                const FF05_SELECTORS = $(`${FF05_SELECTOR_NAME} > select`);
                $(FF05_SELECTORS).select2({
                    minimumResultsForSearch: -1, //no search
                    dropdownParent: element_cb61b
                });
                $(FF05_SELECTORS).on('change', function (e, triggerFetch) {
                    updateQueryString();
                    if (triggerFetch !== 'false')
                        fetchProducts();
                })
            },
            initCompatibilityTable: function () {
                $('.cb60 .mobile-svg').on('click', function (event) {
                    element = $('.cb60 .mobile-svg');
                    $('.cb60 .mobile-svg').toggleClass('closed')

                    if ($('.cb60 .copy-table').hasClass('closed')) {
                        // expand the panel
                        $('.cb60 .copy-table').slideDown();
                        $('.cb60 .copy-table').removeClass('closed');

                        $('.cb60 .button-container').slideDown();
                        $('.cb60 .button-container').removeClass('closed');
                    } else {
                        // collapse the panel
                        $('.cb60 .copy-table').slideUp();
                        $('.cb60 .copy-table').addClass('closed');

                        $('.cb60 .button-container').slideUp();
                        $('.cb60 .button-container').addClass('closed');
                    }
                });

                $(window).resize(function () {
                    if (window.matchMedia('(max-width: 768px)').matches) {
                        //i.e when transition from desktop to mobile, if class has closed then slide up
                        if ($('.cb60 .copy-table').hasClass('closed')) {
                            $('.cb60 .copy-table').slideUp();
                            $('.cb60 .button-container').slideUp();
                            return;
                        }
                    }
                    else {
                        //if transitioning from mobile to desktop, always slide down
                        $('.cb60 .copy-table').slideDown();
                        $('.cb60 .button-container').slideDown();
                    }
                });
            },

            printAssistFirsttimeSetup: function () {


                var html_hide = $('.screen-hide').html();
                $('.screen-2').html(html_hide);
                $('#hide-form').html('');
            },
            edgeSearchDebugMode: function () {
                var debug = canonHelper.getQueryString("debug");
                if (debug) {
                    $('.ff01.edge .debug').show();
                }
                else {
                    $('.ff01.edge .debug').hide();
                }
            },
            toggleRetailerRatings: function () {
                $('#retailerRatings').click(function (e) {
                    e.preventDefault();
                    $('html,body').animate({
                        scrollTop: $(".cb54").offset().top
                    },
                        'slow');
                });
            },
            initEdgesearchboxEnter: function () {

                if ($('.ff01.edge #searchbox').length > 0) {

                    defaultFunctions.edgeSearchDebugMode();

                    $('.ff01.edge #searchbox').keypress(function (e) {
                        if (e.which === 13) {
                            var keyword = $J(this).val();
                            if (keyword.length > 0) {
                                var finalUrl = "?query=" + keyword;
                                var debugValue = canonHelper.getQueryString("debug");
                                if (debugValue) {
                                    finalUrl += "&debug=" + debugValue;
                                }
                                window.location.href = finalUrl;
                            }
                        }
                    });
                }

                if ($('.ff01.edge .icon-svg-search').length > 0) {
                    $('.ff01.edge .icon-svg-search').on('click', function () {
                        var keyword = $('.ff01.edge #searchbox').val();
                        if (keyword.length > 0) {
                            var finalUrl = "?query=" + keyword;
                            var debugValue = canonHelper.getQueryString("debug");
                            if (debugValue) {
                                finalUrl += "&debug=" + debugValue;
                            }
                            window.location.href = finalUrl;
                        }
                    });
                }

                if ($('.ff01.edge #edge-search-order-by')) {
                    var sortByValue = canonHelper.getQueryString("orderby");
                    if (sortByValue) {
                        $('.ff01.edge #edge-search-order-by').val(sortByValue);
                    }

                    $('.ff01.edge #edge-search-order-by').on('change', function () {
                        var keywordValue = canonHelper.getQueryString("query");
                        var filterByValue = canonHelper.getQueryString("filterby");

                        var finalUrl = "?query=" + keywordValue;

                        if (filterByValue) {
                            finalUrl += "&filterby=" + filterByValue;
                        }

                        var debugValue = canonHelper.getQueryString("debug");
                        if (debugValue) {
                            finalUrl += "&debug=" + debugValue;
                        }

                        if ($(this).val()) {
                            finalUrl += "&orderby=" + $(this).val();
                        }
                        window.location.href = finalUrl;
                    });
                }

                if ($('.ff01.edge #edge-search-filter-by')) {
                    var filterByValue = canonHelper.getQueryString("filterby");
                    if (filterByValue) {
                        $('.ff01.edge #edge-search-filter-by').val(filterByValue);
                    }

                    $('.ff01.edge #edge-search-filter-by').on('change', function () {
                        var sortByValue = canonHelper.getQueryString("orderby");
                        var keywordValue = canonHelper.getQueryString("query");
                        var finalUrl = "?query=" + keywordValue;

                        if (sortByValue) {
                            finalUrl += "&orderby=" + sortByValue;
                        }

                        var debugValue = canonHelper.getQueryString("debug");
                        if (debugValue) {
                            finalUrl += "&debug=" + debugValue;
                        }

                        if ($(this).val()) {
                            finalUrl += "&filterby=" + $(this).val();
                        }

                        window.location.href = finalUrl;
                    });
                }
            },
            PartnerfinderGoogleMapInital: function () {
                if (typeof google === 'object' && typeof google.maps === 'object') {
                    var location = document.getElementById('location');
                    var region = document.getElementById('region');
                    var automoplete = new google.maps.places.Autocomplete((location), {
                        types: ['(regions)'],
                        componentRestrictions: { country: region }
                    });
                }
            },
            validateEdgeContactForm: function () {

                $J('#enquiry').keyup(updateCount);
                $J('#enquiry').keydown(updateCount);

                function updateCount() {

                    var limit = $J('#DescriptionLimit').val();
                    var enquiry = $J('#enquiry').val();
                    var currentValue = limit - enquiry.length;
                    var msg = currentValue;
                    if (currentValue < 0) {
                        msg = "Overflow"
                    }
                    $J('#descriptionLength').html(msg);
                }
            },
            SDKAdressGoogleMapInital: function () {
                if (typeof google === 'object' && typeof google.maps === 'object') {
                    var location = document.getElementById('address1');
                    var automoplete = new google.maps.places.Autocomplete((location), {
                        types: ['(regions)'],
                        componentRestrictions: { country: ["au", "nz"] }
                    });

                    autocomplete.addListener("place_changed", function () {
                        var placeResult = autocomplete.getPlace();

                        var place = autocomplete.getPlace();

                        console.log(place);


                        if (!place.geometry) {
                            // User entered the name of a Place that was not suggested and
                            // pressed the Enter key, or the Place Details request failed.
                            window.alert("No details available for input: '" + place.name + "'");
                            return;
                        }

                        var addressComponents = placeResult.address_components;
                        var street = "";
                        var number = "";

                        // loop through addressComponents and find the route and street_number types
                        for (var i = 0, i_len = addressComponents.length; i < i_len; i++) {
                            var addressType = addressComponents[i].types[0];

                            switch (addressType) {
                                case "route":
                                    street = addressComponents[i]["long_name"];
                                    break;

                                case "street_number":
                                    number = addressComponents[i]["long_name"];
                                    break;
                            }
                        }

                        input.value = number + " " + street;
                    });
                }
            },

            SDKDownloadCheckIpAdress: function () {

                var outofAUNZ = $J("#outofAUNZ").val();

                if (outofAUNZ != undefined && outofAUNZ.toLowerCase() === 'true') {
                    var currentForm = $J(".eloqua-ajax-frm");

                    if (currentForm != undefined) {
                        currentForm.find(':input:not(:disabled)').prop('disabled', true)
                        $("#errornotaunz").removeClass("hide--me");
                    }

                }
            },
            cb51LoadData: function () {
                $J('#load-cb51').click(function (event) {
                    var datasourceId = $J("#CB51ImageGalleryDatasourceID").val();
                    var postData = {
                        DatasourceItemId: datasourceId
                    };

                    var post = $J.post('/content-tile/gallery/GetImageGallery', postData);

                    post.done(function (data) {
                        console.log(data);
                    });

                    post.fail(function () {
                        console.log(post);
                    });


                });
            },
            initStackla: function () {

                $J(function () {
                    window.Stackla = { debug: false };
                    requireJSS("//assetscdn.stackla.com/media/js/widget/fluid-embed.js", readyMe);


                });
                $('.leap--stackla__filter #keywordsearch').keypress(function (e) {
                    if (e.which === 13) {
                        var keyword = $J(this).val();
                        var wedget = $('.stackla-widget').data('id');
                        Stackla.WidgetManager.search(wedget, keyword);




                    }
                });
                function readyMe() {
                    $('select').on("change", function () {
                        var dataFilter = $(this).find(":selected").attr('data-filter');
                        var wedget = $('.stackla-widget').data('id');
                        if (dataFilter) {
                            Stackla.WidgetManager.changeFilter(wedget, dataFilter);
                            $('#keywordsearch').val('');
                        }

                    });


                }
                function requireJSS(file, callback) {
                    var head = document.getElementsByTagName("head")[0];
                    var script = document.createElement('script');
                    script.src = file;
                    script.type = 'text/javascript';
                    script.onload = callback;
                    script.onreadystatechange = function () {
                        if (this.readyState == 'complete') {
                            callback();
                        }
                    };
                    head.appendChild(script);
                }
            },

            initMapBlock: function () {
                if ($J('.map-strip').length > 0) {
                    $J('.map-strip').each(function () {
                        var latitude = parseFloat($J(this).attr("data-latitude"));
                        var longitude = parseFloat($J(this).attr("data-longitude"));
                        var location = $J(this).attr("data-location");
                        var placeId = $J(this).attr("data-placeid");
                        var eventDate = $J(this).attr("data-eventstartdate");
                        var containerId = $J(this).attr("data-container");
                        var addressNotExists = true;
                        var infoBox = $('.customInfobox');
                        if (((latitude && longitude) || placeId) && containerId) {
                            //var coordinate = { lat: latitude, lng: longitude };
                            var map = new google.maps.Map(document.getElementById('map-strip'), {
                                //center: coordinate,
                                zoom: 15,
                                scrollwheel: false
                            });
                            var intiMapBlockWithNoAddress = function () {
                                var map = new google.maps.Map(document.getElementById('map-strip'), {
                                    //center: coordinate,
                                    zoom: 15,
                                    scrollwheel: false
                                });
                                var markerWithAddress = new google.maps.Marker({
                                    map: map,
                                    //position: coordinate
                                });
                                $('.customInfobox').addClass("hide--me");
                            };
                            var service = new google.maps.places.PlacesService(map);

                            //var request = {
                            //    location: coordinate,
                            //    radius: '100',
                            //    name: location
                            //};

                            if (placeId) {
                                var request = {
                                    placeId: placeId,
                                    fields: ["formatted_address", "geometry.location", "opening_hours.weekday_text", "url"]
                                };

                                service.getDetails(request, getPlaceDetailsCallback);

                                function getPlaceDetailsCallback(placeDetails, status) {
                                    if (status === google.maps.places.PlacesServiceStatus.OK) {
                                        var marker = new google.maps.Marker({
                                            map: map,
                                            position: placeDetails.geometry.location
                                        });

                                        map.setCenter(placeDetails.geometry.location);

                                        if (placeDetails != undefined) {
                                            if (placeDetails.formatted_address != undefined && location != undefined && location.length > 0) {
                                                infoBox.find('.location-address .address').html(placeDetails.formatted_address);
                                                infoBox.find('.location-address').removeClass("hide--me");
                                                addressNotExists = false;
                                            }
                                            if (placeDetails.opening_hours != undefined && placeDetails.opening_hours.weekday_text != undefined) {
                                                $.each(placeDetails.opening_hours.weekday_text, function (i) {
                                                    var dayofWeek = placeDetails.opening_hours.weekday_text[i];
                                                    if (dayofWeek.indexOf(eventDate) != -1) {
                                                        infoBox.find('.open-hours').html(dayofWeek.replace(eventDate + ":", "").toLowerCase().replace(/ /g, "").replace("–", " - "));
                                                        infoBox.find('.location-open-hours').removeClass("hide--me");

                                                    }
                                                });
                                            }
                                            if (placeDetails.url != undefined) {
                                                infoBox.find('.google-link').attr('href', placeDetails.url);
                                                infoBox.find('.google-link').removeClass("hide--me");

                                            }
                                        }
                                        if (addressNotExists) {
                                            intiMapBlockWithNoAddress(map, coordinate);
                                        }
                                    }
                                }
                            }
                            else {
                                const myLatLng = { lat: latitude, lng: longitude };
                                const map = new google.maps.Map(document.getElementById("map-strip"), {
                                    zoom: 13,
                                    center: myLatLng
                                });
                                new google.maps.Marker({
                                    position: myLatLng,
                                    map,
                                    title: location
                                });
                            }


                        }
                    });
                }
            },

            initCarousel: function () {
                $(".carousel .carousel-cell ul.flexbox").each(function (index, item) {
                    if ($(item).find("li").length == 0) {
                        $(item).remove();
                    }
                });
            },

            initImpersonation: function () {

                $('#impersonate-user').click(function () {
                    if ($('#impersonated-user').is(':visible')) {
                        var username = $("#impersonated-user").val();
                        if (username && username != '') {
                            window.location = window.location.origin + '/auth/account/impersonate?username=' + username;
                        }
                        else {
                            $("#impersonated-user").animate({ width: 'toggle' }, 350);
                        }
                    }
                    else {
                        $("#impersonated-user").animate({ width: 'toggle' }, 350);
                    }
                });
            },

            canonsInlineJS: function () {
                var mobilizer = (function () {
                    var ua = navigator.userAgent;
                    return {
                        isTouch: function () {
                            return 'ontouchstart' in document.documentElement;
                        },
                        isMobile: function () {
                            return (function (a) { return /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4)) })(navigator.userAgent || navigator.vendor || window.opera);
                        },
                        isAndroidStock: function () {
                            ua = navigator.userAgent;
                            rtn = (ua.indexOf('Mozilla/5.0') > -1) && (ua.indexOf('Android') > -1) && !(ua.indexOf('Chrome') > -1) && (ua.indexOf('Version') > -1);
                            return rtn;
                        },
                        appendClass: function (a) {
                            document.documentElement.className += ' ' + a;
                            return true;
                        }
                    };
                })();

                var isTouch = mobilizer.isTouch() ? mobilizer.appendClass('touch') : false;
                var isMobile = mobilizer.isMobile() ? mobilizer.appendClass('mobile') : false;
                var isAndroidStock = mobilizer.isAndroidStock() ? mobilizer.appendClass('android stock') : false;

                !function (n, t) {
                    "$:nomunge";
                    var u, e = n.jQuery || n.Cowboy || (n.Cowboy = {});
                    e.throttle = u = function (n, u, o, i) {
                        function r() {
                            function e() {
                                c = +new Date, o.apply(f, d)
                            }

                            function r() {
                                a = t
                            }

                            var f = this, g = +new Date - c, d = arguments;
                            i && !a && e();
                            a && clearTimeout(a);
                            i === t && g > n ? e() : u !== !0 && (a = setTimeout(i ? r : e, i === t ? n - g : n))
                        }

                        var a, c = 0;
                        return "boolean" != typeof u && (i = o, o = u, u = t), e.guid && (r.guid = o.guid = o.guid || e.guid++), r
                    }, e.debounce = function (n, e, o) {
                        return o === t ? u(n, e, !1) : u(n, o, e !== !1)
                    }
                }(this);
            },

            theFarmRemoveEmptyList: function () {
                $('.the-farm li').each(function () {
                    var el = $(this);
                    if (!$.trim($(this).html()).length) {
                        $(this).remove();
                        canonHelper.tileMarginFix($J(el).parent('ul'));
                    }
                });
            },

            loadMoreFeed: function () {
                var templates = $J('#feed-item-template').html();
                var feed = $J('#feed-list');

                var isNextStickyTilePageAvailable = $J('.load-more-feed button').attr('data-is-next-sticky-tile-page-available');
                var isNextContentFeedTilePageAvailable = $J('.load-more-feed button').attr('data-is-next-content-feed-tile-page-available');
                var currentStickyTilePage = $J('.load-more-feed button').attr('data-current-sticky-tile-page');
                var currentContentFeedTilePage = $J('.load-more-feed button').attr('data-current-content-feed-tile-page');
                var totalcontentFeedFirstIndex = $J('.load-more-feed button').attr('data-total-content-feed-first-index');
                var isLastPage = $J('.load-more-feed button').attr('data-is-last-page');
                var isFirstTimeFetchingFullContentFeed = $J('.load-more-feed button').attr('data-is-first-time-fetching-full-content-feed');

                $J('.load-more-feed button').off('click');

                $J(document).on('click', '.load-more-feed button', function () {

                    var itemPath = $J(this).attr('data-item-path');
                    var datasourceId = $J(this).attr('data-datasource-id');

                    var postData = {
                        ItemPath: itemPath,
                        DatasourceItemId: datasourceId,
                        StickyTilePageIndex: isNextStickyTilePageAvailable ? currentStickyTilePage + 1 : currentStickyTilePage,
                        ContentFeedPageIndex: isNextContentFeedTilePageAvailable ? currentContentFeedTilePage + 1 : currentContentFeedTilePage,
                        StopFetchingStickyTiles: !isNextStickyTilePageAvailable,
                        TotalcontentFeedFirstIndex: totalcontentFeedFirstIndex,
                        IsLastPage: isLastPage
                    };

                    if (isFirstTimeFetchingFullContentFeed) {
                        postData.ContentFeedPageIndex = 0;
                    }

                    $J(this).prop('disabled', true).addClass('loading');

                    var post = $J.post('/content-tile/contenttile/contentfeedpage', postData);

                    post.done(function (data) {
                        var result = Mustache.to_html(templates, data);

                        feed.append(result);

                        if (data.IsLastPage) {
                            $J('.load-more-feed button').parent().hide();
                        } else {
                            isNextStickyTilePageAvailable = data.IsNextStickyTilePageAvailable;
                            isNextContentFeedTilePageAvailable = data.IsNextContentFeedTilePageAvailable;
                            currentStickyTilePage = data.CurrentStickyTilePage;
                            currentContentFeedTilePage = data.CurrentContentFeedTilePage;
                            totalcontentFeedFirstIndex = data.TotalContentFeedFirstIndex;
                            isFirstTimeFetchingFullContentFeed = data.IsFirstTimeFetchingFullContentFeed;
                            isLastPage = data.IsLastPage;
                        }
                    });

                    post.fail(function () {

                    });

                    post.always(function () {
                        $J('.load-more-feed button').prop('disabled', false).removeClass('loading');
                    });
                });
            },

            changeMetaAttributeValue: function () {
                var attributes = $J('[name="og:image"]');
                $J(attributes).each(function () {
                    var currentContent = $J(this).prop('content');
                    var modifiedContent = window.location.origin + "/" + currentContent.substring(currentContent.indexOf("-/"));
                });
            },

            

            initiateNoneClickableLinks: function () {
                if ($J('.none-clickable-link').length > 0) {
                    $J('.none-clickable-link').on("click", function (event) {
                        event.preventDefault();
                    });
                }
            },

            initPartnerFinder: function () {
                $(".partner-finder .icon-svg-search").on("click", function () {
                    $(".partner-finder").submit();
                });
            },

            filterProductList: function (key) {
                if ($J("ul.product-listing-component").length > 0) {
                    if (key === "all") {
                        $J("ul.product-listing-component li").each(function () {
                            $J(this).removeClass("hide--me");
                        });
                    } else {
                        $J("ul.product-listing-component li").each(function () {
                            var currentListFilterKeys = $J(this).attr("data-filter-key");
                            if (currentListFilterKeys.indexOf(key) !== -1) {
                                $J(this).removeClass("hide--me");
                            } else {
                                $J(this).addClass("hide--me");
                            }
                        });
                    }
                    var filterProducts = $(".product-listing-component > li:not(.hide--me)").length;
                    $(".filterProducts").text(filterProducts);
                }
            },

            initiateDropDownWithDynamicCTA: function () {
                if ($J("select.cb26-option").length > 0) {
                    $J("select.cb26-option").on("change", function () {
                        var optionSelected = $J("option:selected", this);
                        if (optionSelected.length > 0) {
                            var ctaTitle = $J(optionSelected).attr("data-cta-title");
                            var ctaLink = $J(optionSelected).attr("data-cta-link");
                            var cta = $J(this).closest("div").find("a.cb26-cta");
                            if (cta.length > 0) {
                                $J(cta).text(ctaTitle);
                                $J(cta).attr("href", ctaLink);
                            }

                            var valueSelected = optionSelected.val();
                            var editFrameOptionsExist = $J("div.editframe-option").length > 0;
                            if (editFrameOptionsExist) {
                                $J("div.editframe-option").each(function () {
                                    if ($J(this).attr("data-itemid") === valueSelected) {
                                        $J(this).removeClass("hide--me");
                                    } else {
                                        if (!$J(this).hasClass("hide--me")) {
                                            $J(this).addClass("hide--me");
                                        }
                                    }
                                });
                            }
                        }
                    });
                }
            },

            contentFeedEventsLoadMoreCall: function () {
                $(".load-more-events")
                    .each(function (index, element) {
                        if ($(this).attr("data-is-last-page") == "True") {
                            $(this).hide();
                        } else {
                            $(this).show();
                        }
                    });
                var loadmoreButton = $J(".load-more-events");
                loadmoreButton.off('click');
                loadmoreButton.on("click",
                    function () {
                        var $this = $J(this);
                        var currentPageIndex = $this.attr('data-current-index');
                        var totalProductDisplayedOnPage = $this.attr('data-total-events-displayed-on-page');
                        var isLastPage = $this.attr('data-is-last-page');
                        var containerId = $this.attr('data-container-id');
                        var currentItemId = $this.attr('data-current');
                        var dataSourceId = $this.attr('data-datasource');
                        var iscollectivemajoreventfeed = $this.attr('data-iscollectivemajoreventfeed');
                        $J(this).blur();
                        if (isLastPage.toLowerCase() == "false" || !isLastPage) {
                            currentPageIndex++;
                        }
                        var template;
                        // Try loading the external template files
                        $.when(
                            $.get("/mustachetemplates/content-listing-feed.html",
                                function (source) {
                                    template = source;
                                })
                        )
                            .then(function () {
                                // Continue to the main script if templates are loaded successfully
                                var feed = $J('#' + containerId);
                                canonHelper.showSpinner();
                                var postData = {
                                    contentFeedDataSourceId: dataSourceId,
                                    currentItemId: currentItemId,
                                    pageIndex: currentPageIndex,
                                    totalEventsDisplayedOnPage: totalProductDisplayedOnPage,
                                    isCollectiveMajorEventFeed: iscollectivemajoreventfeed
                                };
                                var post = $J.post('/content-tile/explore/getrelatedeventsfeed', canonHelper.addAntiForgeryToken(postData));

                                post.done(function (data) {
                                    if (data != "") {
                                        if (data.ContentListingFeedSkinnyTiles != undefined) {
                                            var result = Mustache
                                                .to_html(template,
                                                    { ContentListingFeedSkinnyTiles: data.ContentListingFeedSkinnyTiles });

                                            feed.append(result);

                                            canonHelper.tileMarginFix($J(feed));

                                            if (data.IsLastPage) {
                                                $this.hide();
                                            } else {
                                                $this.show();
                                            }

                                            $this
                                                .attr('data-current-index', data.CurrentPageIndex);
                                            $this
                                                .attr('data-total-events-displayed-on-page',
                                                    data.TotalEventsDisplayedOnPage);
                                            $this.attr('data-is-last-page', data.IsLastPage);

                                            $this.find(".events-left")
                                                .html("(" + data.TotalEventsLeftCount + " events left)");
                                        }
                                    }
                                    canonHelper.hideSpinner();
                                });

                                post.fail(function () {
                                    canonHelper.hideSpinner();
                                });

                            },
                                function () {
                                    // templates not loaded
                                    var templateError =
                                        'Error: Could not load plugin templates. Check the paths and ensure they have been uploaded. Paths will be wrong if you do not run this from a web server.';
                                    console.log(templateError);
                                });
                    });
            },

            requestPdfReports: function () {
                $J(".select-report-per-year")
                    .change(function () {
                        canonHelper.showSpinner();
                        var resultElement =
                            $J(this).closest(".report-peryear-container").find(".result-report-peryear");
                        var caption = $J(this).attr("data-caption");
                        var datasource = $J(this).attr("data-source");
                        var selectedOption = $J("option:selected", this);
                        var selectedYear = selectedOption ? selectedOption.val() : 0;
                        var postData = { datasource: datasource, report: caption, year: selectedYear };
                        var data = canonHelper.addAntiForgeryToken(postData);
                        var post = $J.post('/content/report/getreportsbypublishedyear', data);

                        post.done(function (data) {
                            if (data !== "") {
                                $J(resultElement).html(data);
                            }

                            canonHelper.hideSpinner();

                        });
                        post.fail(function () {
                            canonHelper.hideSpinner();
                        });
                    });
            },

            AddFavouriteContent: function () {
                $J(".likecontent").off("click");

                $J(document)
                    .on("click",
                        ".likecontent",
                        function () {
                            var $this = $J(this);
                            var id = $this.attr("data-id");
                            var type = $this.attr("data-type");
                            var titletype = GetWishListType(type);
                            canonHelper.showSpinner();
                            var post = $J.post("/canonhub/mycanon/addfavourite",
                                {
                                    id: id,
                                    type: type
                                });

                            post.done(function (data) {
                                if (data != "" && data.IsSucess) {
                                    $this.removeClass("icomoon-Favorite_Outlined");
                                    $this.removeClass("likecontent");
                                    $this.addClass("icomoon-Close");
                                    $this.addClass("unlikecontent");
                                    $this.attr("title", "Unlike this " + titletype);
                                }
                                canonHelper.hideSpinner();
                            });
                            post.fail(function (jqXhr, textStatus, errorThrown) {
                                if (jqXhr.status == "401") {
                                    var htmlText = "<p>It looks like you're not logged into My Canon. Please login or sign up to add to your favourites.</p>";
                                    htmlText += "<a href = '/auth/account/signin?redirectUrl=" + window.location.pathname + "' >Sign in to My Canon</a>";
                                    $J('.global-error-message-body').html(htmlText);
                                    var modelInst = $('[data-remodal-id=globalErrorMessage]').remodal();
                                    modelInst.open();
                                }
                                canonHelper.hideSpinner();
                            });

                        });
            },

            DeleteFavouriteContent: function () {
                if ($J('.favoriteModel').length) {
                    var model = '<div id="modeldialogoverlay"></div><div class="remodal" data-remodal-id="remove_favorite" data-remodal-options="hashTracking: false"><div class="modal-body-text"></div><br /><div class="modal-footer"></div></div>'
                    $J('.favoriteModel').append(model);
                }
                $J(".unlikecontent").off("click");
                $J(document)
                    .on("click",
                        ".unlikecontent",
                        function () {
                            var $this = $J(this);
                            var id = $this.attr("data-id");
                            var type = $this.attr("data-type");
                            render(id, type);

                        });
                $(document).on('click', '.btnfavoritecontinue', function () {
                    if ($(this).data("id") != null && $(this).data("id") != undefined) {
                        var type = $(this).data("type");
                        continueefavorite($(this).data("id"), type)
                    }
                });
                $(document).on('click', '.btnfavoritecancel', function () {
                    cancelfavorite();
                });
                function render(id, type) {
                    var winW = window.innerWidth;
                    var winH = window.innerHeight;
                    $("#dialogoverlay").show();
                    $("#dialogoverlay").attr("height", winH + "px")
                    var confirmtype = type !== 'Event' ? 'Article' : type;

                    $(".modal-body-text").html('Are you sure you want to remove this ' + confirmtype.toLowerCase() + '?');
                    $(".modal-footer").html('<button class="btn--3 btnfavoritecancel">Cancel</button> <button class="btn--2 btnfavoritecontinue"  data-type="' + type + '" data-id="' + id + '" >Yes, remove ' + confirmtype.toLowerCase() + '</button> ');
                    var modelInst = $('[data-remodal-id=remove_favorite]').remodal();
                    modelInst.open();
                }
                function cancelfavorite() {
                    var modelInst = $('[data-remodal-id=remove_favorite]').remodal();
                    modelInst.close();

                    $("#dialogoverlay").hide();
                }
                function continueefavorite(id, type) {
                    var modelInst = $('[data-remodal-id=remove_favorite]').remodal();
                    modelInst.close();
                    $("#dialogoverlay").hide();
                    canonHelper.showSpinner();
                    var $this = '';
                    if ($J("span.unlikecontent[data-id='" + id + "']").length) {
                        $this = $J("span.unlikecontent[data-id='" + id + "']");
                    }
                    var post = $J.post("/canonhub/mycanon/removefavourite",
                        {
                            id: id,
                            type: type
                        });

                    post.done(function (data) {
                        if (data != "" && data.IsSucess) {
                            if ($J('ul.wishlist-container').length) {
                                var wishlistItem = $this.closest("li");
                                wishlistItem.remove();
                            }
                            else {
                                $this.removeClass("icomoon-Favorite_Filled");
                                $this.removeClass("icomoon-Close");
                                $this.removeClass("unlikecontent");
                                $this.addClass("icomoon-Favorite_Outlined");
                                $this.addClass("likecontent");
                            }
                        }
                        canonHelper.hideSpinner();
                    });

                    post.fail(function () {
                        canonHelper.hideSpinner();
                    });
                }
            },

            wishListEvents: function () {

                function IsFevoriate(item, items) {
                    return ($.inArray(item, items) > -1);
                }
                $J("ul.wishlist-container > li").each(function () {
                    var $this = $J(this).find(".icomoon-Favorite_Outlined");
                    $this.removeClass("icomoon-Favorite_Outlined");
                    $this.removeClass("likecontent");
                    $this.addClass("icomoon-Close");
                    $this.addClass("unlikecontentwishlist");
                });
                if ($J(".likecontent").length > 0 || $(".unlikecontent").length > 0) {
                    var post = $J.get("/canonhub/mycanon/getmemberfavourites", {});
                    post.done(function (data) {
                        $($("span.likecontent"), $("span.unlikecontent")).each(function () {
                            var item = $(this).attr("data-id");
                            if (data != "" && IsFevoriate(item, data)) {
                                var type = GetWishListType($(this).attr("data-type"));
                                $(this).removeClass("icomoon-Favorite_Outlined");
                                $(this).removeClass("likecontent");
                                $(this).addClass("icomoon-Close");
                                $(this).addClass("unlikecontent");
                                $(this).attr("title", "Unlike this " + type);
                            }
                            else {
                                var type = GetWishListType($(this).attr("data-type"));
                                $(this).addClass("icomoon-Favorite_Outlined");
                                $(this).addClass("likecontent");
                                $J(this).removeClass("icomoon-Favorite_Filled");
                                $(this).removeClass("icomoon-Close");
                                $(this).removeClass("unlikecontent");
                                $(this).attr("title", "Like this " + type);
                            }
                        });

                    });

                }
                $J(".icomoon-Favorite_Filled.unlikecontent").each(function () {
                    var type = GetWishListType($J(this).attr("data-type"));
                    $J(this).removeClass("icomoon-Favorite_Filled");
                    $J(this).addClass("icomoon-Close");
                    $J(this).attr("title", "Unlike this " + type);
                });
                $J(".icomoon-Favorite_Outlined.likecontent").each(function () {
                    var type = GetWishListType($J(this).attr("data-type"));
                    $J(this).attr("title", "Like this " + type);
                });
                $J(".wishlist-filter .wishlist-filter-select").on("click", function () {
                    var $this = $J(this);
                    if ($this.attr("data-content-type") === "all") {
                        $("ul.wishlist-container > li").fadeIn("slow");;
                    } else {
                        var $el = $("." + $this.attr("data-content-type")).fadeIn("slow");;
                        $("ul.wishlist-container > li").not($el).hide();
                    }
                    $J(".wishlist-filter .wishlist-filter-select").removeClass("active");
                    $(this).addClass("active");
                });

                $J(".unlikecontentwishlist").off("click");
                $J(document)
                    .on("click",
                        ".unlikecontentwishlist",
                        function () {
                            var $this = $J(this);
                            var wishlistItem = $J(this).closest("li");
                            var id = $this.attr("data-id");
                            var type = $this.attr("data-type");
                            canonHelper.showSpinner();
                            var post = $J.post("/canonhub/mycanon/removefavourite",
                                {
                                    id: id,
                                    type: type
                                });

                            post.done(function (data) {
                                if (data != "" && data.IsSucess) {
                                    wishlistItem.remove();
                                }
                                canonHelper.hideSpinner();
                            });

                            post.fail(function () {
                                canonHelper.hideSpinner();
                            });
                        });
            },

            highlightCarousel: function () {
                $(".cb02a, .cb02").each(function () {
                    $J(this).find(" .carousel-content > div").first().css("opacity", "1");
                });
            },
            initProductImageGalleryButton: function () {
                $('.cb-53-button.right').click(function (e) {
                    $('.cb53 .feature-image').slick('slickNext');
                });
                //

                $('.cb53 .mobile-feature-image').on('init', function (event, slick) {
                    // event subscriber goes here
                    let slickDots = $('.cb53 .slick-dots > li').length || 0;
                    if (slickDots && slickDots > 1) {
                        $('.mobile-feature-image .slick-dots').css({
                            gridTemplateColumns: `repeat(${slickDots}, 1fr`,
                            display: 'grid'
                        })
                        // $('.mobile-feature-image .slick-dots').css('display', 'grid !important')
                    }
                });
                $(window).on('resize orientationChange', function (e) {
                    let slickDots = $('.cb53 .slick-dots > li').length || 0;
                    if (slickDots) {
                        $('.mobile-feature-image .slick-dots').css({
                            display: 'grid',
                            gridTemplateColumns: `repeat(${slickDots}, 1fr`,
                        })
                    }
                });


                $('.cb-53-button.left').click(function (e) {
                    $('.cb53 .feature-image').slick('slickPrev');
                });

                $('.cb53 .mobile-feature-image').slick({
                    infinite: false,
                    slidesToShow: 2,
                    slidesToScroll: 1,
                    dots: true,
                    adaptiveHeight: false,
                    mobileFirst: true,
                    arrows: false,
                    responsive: [
                        { breakpoint: 843, settings: { slidesToShow: 2 } },
                        { breakpoint: 747, settings: { slidesToShow: 2 } },
                        { breakpoint: 320, settings: { slidesToShow: 1 } },
                    ]
                });

                $('.cb53 .feature-image').slick({
                    infinite: false,
                    slidesToShow: 1,
                    slidesToScroll: 1,
                    autoplay: false,
                    // autoplaySpeed: 3000,
                    dots: false,
                    pauseOnDotsHover: true,
                    adaptiveHeight: true,
                    mobileFirst: true,
                    arrows: false,
                }).on('afterChange', (e, slick, currentSlide, nextSlide) => {

                    const trueCurrentSlide = parseInt(currentSlide + 1)
                    const totalSlides = $('.cb53 .slide-preview-tiles > div').length

                    $('.cb53 .slide-preview-tiles > div').removeClass('active')
                    $('.cb53 .slide-preview-tiles > div:nth-child(' + trueCurrentSlide + ')').addClass('active')

                    if (currentSlide >= 1) {
                        $('.cb-53-button.left').addClass('active')
                    } else {
                        $('.cb-53-button.left').removeClass('active')
                    }
                    if (trueCurrentSlide === totalSlides) {
                        $('.cb-53-button.right').removeClass('active')
                    } else {
                        $('.cb-53-button.right').addClass('active')
                    }
                });


                $('.cb53 .slide-preview-tiles > div').on('click', (e) => {
                    $('.cb53 .slide-preview-tiles > div').removeClass('active')
                    $(e.target).addClass('active');
                    $('.cb53 .feature-image').slick('slickGoTo', e.target.dataset.index)
                })
            },
            initPluginFocus: function () {
                Focus.init({
                    elementID: '',
                    zoomFactor: '250%'
                });
            },
            initIsAlsoAvailable: function () {
                const addSliderOffset = ({ element, delay }) => {
                    const offset = 36
                    const draggable = element.children('.draggable')
                    //draggable dots
                    const draggableHeight = draggable.height()
                    setTimeout(() => {
                        draggable.attr('style', `height: ${draggableHeight + offset}px !important;`)
                    }, delay)
                }
                $('.cb57 .also-available-slider').on('init', function (event, slick) {
                    // addSliderOffset({
                    //     element: $(this),
                    //     delay: 500
                    // })
                    //dynamic dots
                    const dots = slick.$dots && slick.$dots[0] ? slick.$dots[0].childElementCount : 0
                    $(this).find('.slick-dots')
                        .attr('style', `display: grid !important; grid-template-columns: repeat(${dots}, 1fr) !important`)
                    dots === 0 ? $('.cb57 .arrow').addClass('hidden') : $('.cb57 .arrow').removeClass('hidden')
                });
                $('.cb57 .also-available-slider').slick({
                    infinite: false,
                    slidesToShow: 1,
                    slidesToScroll: 1,
                    autoplay: false,
                    autoplaySpeed: 3000,
                    dots: true,
                    pauseOnDotsHover: true,
                    adaptiveHeight: true,
                    swipeToSlide: true,
                    mobileFirst: true,
                    arrows: false,
                    responsive: [
                        { breakpoint: 1300, settings: { slidesToShow: 2 } },
                        { breakpoint: 1200, settings: { slidesToShow: 1 } },
                        { breakpoint: 330, settings: { slidesToShow: 1 } },
                        // {breakpoint: 330, settings: {slidesToShow: 2}},
                    ]
                }).on('afterChange', (e, slick, currentSlide, nextSlide) => {
                    const trueCurrentSlide = parseInt(currentSlide + 1)
                    const slickDots = slick.$dots && slick.$dots[0] ? slick.$dots[0].childElementCount : 0;
                    if (currentSlide >= 1) {
                        $(e.currentTarget).siblings('.left').addClass('active')
                    } else {
                        $(e.currentTarget).siblings('.left').removeClass('active')
                    }
                    if (trueCurrentSlide === slickDots) {
                        $(e.currentTarget).siblings('.right').removeClass('active')
                    } else {
                        $(e.currentTarget).siblings('.right').addClass('active')
                    }
                    // addSliderOffset({
                    //     element: $(e.currentTarget),
                    //     delay: 500,
                    // })
                });
                $('.also-available-container>.left').click(function (e) {
                    $(this).siblings('.also-available-slider').slick('slickPrev');
                });
                $('.also-available-container>.right').click(function (e) {
                    $(this).siblings('.also-available-slider').slick('slickNext');
                });
                let onResizeTimer = null;
                $(window).on('resize orientationChange', function (e) {
                    if (onResizeTimer !== null) {
                        clearTimeout(onResizeTimer)
                    }
                    onResizeTimer = setTimeout(() => {
                        $('.cb57 .also-available-slider').each(function () {
                            const dots = $(this).find('.slick-dots > li').children().length
                            if (dots === 0) {
                                $('.cb57 .arrow').addClass('hidden')
                            } else {
                                $('.cb57 .arrow').removeClass('hidden')
                                $(this).find('.slick-dots')
                                    .attr('style', `display: grid !important; grid-template-columns: repeat(${dots}, 1fr) !important`);
                            }
                        });
                        onResizeTimer = null;
                    },
                        100)
                });
            },
            initRetailerRatings: function () {
                const initialiseSlicks = () => {

                    $('.cb54 .retailer-ratings').on('init', function (event, slick) {


                        const dots = slick.$dots && slick.$dots[0] ? slick.$dots[0].childElementCount : 0
                        $(this).find('.slick-dots')
                            .attr('style', `display: grid !important; grid-template-columns: repeat(${dots}, 1fr) !important`)
                        if (dots === 0) {
                            $(this).siblings('.arrow').attr('style', `display: none;`)
                            $(this).closest('.retailer-ratings-container').attr('style', `grid-template-columns:1fr;`)
                            $(this).children('.slick-list').attr('style', `display:grid;justify-items:center`)
                            $(this).find('.slick-list>.slick-track>.slick-active').attr('style', `display:grid;justify-items:center`)

                        }

                    });

                    $('.cb54 .retailer-ratings').slick({
                        infinite: false,
                        slidesToShow: 1.4,
                        slidesToScroll: 1,
                        autoplay: false,
                        autoplaySpeed: 3000,
                        dots: true,
                        pauseOnDotsHover: true,
                        adaptiveHeight: true,
                        mobileFirst: true,
                        arrows: false,
                        responsive: [
                            { breakpoint: 1130, settings: { slidesToShow: 6 } },
                            { breakpoint: 950, settings: { slidesToShow: 5 } },
                            { breakpoint: 830, settings: { slidesToShow: 4 } },
                            { breakpoint: 500, settings: { slidesToShow: 3 } },
                            { breakpoint: 390, settings: { slidesToShow: 2 } },
                        ]
                    }).on('afterChange', (e, slick, currentSlide, nextSlide) => {

                        const trueCurrentSlide = parseInt(currentSlide + 1)
                        const slickDots = slick.$dots && slick.$dots[0] ? slick.$dots[0].childElementCount : 0;

                        if (currentSlide >= 1) {
                            $(e.currentTarget).siblings('.left').addClass('active')
                        } else {
                            $(e.currentTarget).siblings('.left').removeClass('active')
                        }
                        if (trueCurrentSlide === slickDots) {
                            $(e.currentTarget).siblings('.right').removeClass('active')
                        } else {
                            $(e.currentTarget).siblings('.right').addClass('active')
                        }
                    })
                }

                initialiseSlicks()

                $('.retailer-ratings-container>.left').click(function (e) {
                    $(this).siblings('.retailer-ratings').slick('slickPrev');
                });
                $('.retailer-ratings-container>.right').click(function (e) {
                    $(this).siblings('.retailer-ratings').slick('slickNext');
                });


                let onResizeTimer = null;
                $(window).on('resize orientationChange', function (e) {
                    if (onResizeTimer !== null) {
                        clearTimeout(onResizeTimer)
                    }
                    onResizeTimer = setTimeout(() => {

                        $('.cb54 .retailer-ratings').each(function () {
                            const dots = $(this).find('.slick-dots > li').children().length

                            if (dots === 0) {
                                $(this).siblings('.arrow').attr('style', `display: none !important;`)
                                $(this).parent('.retailer-ratings-container').attr('style', `grid-template-columns:100% !important`)
                                $(this).children('.slick-list').attr('style', `display:grid;justify-items:center`)
                                $(this).find('.slick-list>.slick-track>.slick-active').attr('style', `display:grid;justify-items:center`)

                            } else {
                                $(this).find('.slick-dots')
                                    .attr('style', `display: grid !important; grid-template-columns: repeat(${dots}, 1fr) !important`);
                                $(this).siblings('.arrow').attr('style', `display: grid;`)
                                $(this).closest('.retailer-ratings-container').attr('style', `grid-template-columns: 60px calc(100% - 220px) 60px;`)
                                $(this).children('.slick-list').attr('style', `display:inherit;`)
                                $(this).find('.slick-list>.slick-track>.slick-active').attr('style', `display:inherit`)
                            }
                        });
                        onResizeTimer = null;
                    },
                        100)
                });

            },
            initScrollToNextElement: function () {
                $J('.scroll-to-next-element').on('click', function (event) {
                    event.preventDefault();
                    var rootElement = $J(this).closest('*[data-component-wrapper="true"]');
                    if (rootElement.length > 0) {
                        var nextElement = $J(rootElement).next('div');
                        var scrollToLocation = 0;
                        if (nextElement.length > 0) {
                            scrollToLocation = $J(nextElement).offset().top;
                        }
                        else {
                            nextElement = $J(rootElement).next('section');
                            if (nextElement.length > 0) {
                                scrollToLocation = $J(nextElement).offset().top;
                            }
                            else {
                                var topLevelElement = $J(rootElement).parentsUntil($J('body'));
                                nextElement = $J(topLevelElement).next('div');
                                if (nextElement.length > 0) {
                                    scrollToLocation = $J(nextElement).offset().top;
                                }
                                else {
                                    nextElement = $J(topLevelElement).next('section');
                                    if (nextElement.length > 0) {
                                        scrollToLocation = $J(nextElement).offset().top;
                                    }
                                }
                            }
                        }

                        if (scrollToLocation > 0) {
                            if ($J('.gl01.sticknav').length > 0) {
                                scrollToLocation = (scrollToLocation - 130);
                            }

                            $('html, body').animate({ scrollTop: scrollToLocation }, 1000);
                        }
                    }
                });
            },

            PressKitDownload: function () {
                $J("#press-kit-dler").change(function () {
                    var downloadUrl = $("#press-kit-dler option:selected").val();
                    if (downloadUrl.length > 0) {
                        $J(".press-kit-download").attr("href", $("#press-kit-dler option:selected").val());
                    }
                });
            },

            contentFeedLoadMore: function () {
                $J('.farm-load-more-feed a').on('click', function (e) {
                    e.preventDefault();
                    canonHelper.showSpinner();
                    var loadMoreEl = $J(this);
                    var loadMoreContainerEl = $J(this).closest('.farm-load-more-feed');
                    var contentFeedFarm = $J(loadMoreContainerEl).siblings(".content-feed-farm");
                    if (contentFeedFarm.length > 1) {
                        contentFeedFarm = $J(loadMoreContainerEl).prev(".content-feed-farm");
                    }
                    var currentPageIndex = $J(this).attr("data-current-page");
                    var currentPageId = $J(contentFeedFarm).attr('data-page-id');
                    var tileContainer = $J(contentFeedFarm).find('ul');
                    var pageToRender = parseInt(currentPageIndex) + 1;

                    var postData = {
                        DataSource: contentFeedFarm.attr("data-source"),
                        PageIndex: pageToRender,
                        CurrentPageId: currentPageId
                    };

                    $J(this).blur();

                    var data = canonHelper.addAntiForgeryToken(postData);
                    var post = $J.post('/content-tile/thefarm/getcontentfeedfarm', data);

                    post.done(function (data) {
                        var template;
                        // Try loading the external template files
                        $.when($.get("/mustachetemplates/content-listing-feed.html", function (source) { template = source; }))
                            .then(function () {

                                if (data.ContentListingFeedSkinnyTiles && data.ContentListingFeedSkinnyTiles.length > 0) {
                                    var result = Mustache.to_html(template, data);

                                    $J(tileContainer).append(result);

                                    $J(tileContainer).slideDown(500);
                                    canonHelper.constructVideoElement();
                                    canonHelper.tileMarginFix($J(tileContainer));

                                }

                                if (data && data.IsNextPageAvailable) {
                                    var loadMoreText = "<span>Load more " + data.TilesTypeForLoadMore + "</span><br>" + "(" + data.NextItemToDisplayed + ") " + data.TilesCounterForLoadMore + " left";
                                    $J(loadMoreEl).html(loadMoreText);
                                    $J(loadMoreEl).attr("data-current-page", data.CurrentPageIndex);
                                    $J(loadMoreContainerEl).removeClass('hide--me');
                                } else {
                                    if (!loadMoreContainerEl.hasClass('hide--me')) {
                                        loadMoreContainerEl.addClass('hide--me');
                                    }
                                }

                                canonHelper.hideSpinner();

                            },
                                function () {
                                    // templates not loaded
                                    var templateError = 'Error: Could not load plugin templates. Check the paths and ensure they have been uploaded. Paths will be wrong if you do not run this from a web server.'; console.log(templateError);
                                    canonHelper.hideSpinner();
                                });
                    });

                    post.fail(function () {
                        canonHelper.hideSpinner();
                    });

                    post.always(function () {
                        //$J('.load-more-feed button').prop('disabled', false).removeClass('loading');
                    });
                });
            },

            forms: function () {

                $('a.go-back').click(function (e) {
                    window.history.back();
                });

                $(window).scroll(function (event) {
                    var hT = $("footer").offset().top,
                        hH = $("footer").outerHeight(),
                        wH = $(window).height(),
                        wS = $(this).scrollTop();
                    buttonHeight = $(".mc07 .form-submit").outerHeight();
                    //  wS + buttonHeight + buttonHeight > (hT - hH - buttonHeight) 
                    if (wS + hH > (hT - hH)) {
                        $(".mc07 .form-submit").addClass("mycanon-stickynav-form-submit");
                    }
                    else {
                        $(".mc07 .form-submit").removeClass("mycanon-stickynav-form-submit");
                    }
                });
                var detectOperatingSystemName = function () {
                    /*Default OS is windows*/
                    var osName = "Windows";
                    if (navigator.appVersion.indexOf("Win") != -1) osName = "Windows";
                    else if (navigator.appVersion.indexOf("Mac") != -1) osName = "Mac";
                    else if (navigator.appVersion.indexOf("X11") != -1) osName = "UNIX";
                    else if (navigator.appVersion.indexOf("Linux") != -1) osName = "Linux";

                    return osName;
                }

                $J("form[class*='form']").submit(function (event) {
                    try {
                        //disable all submit buttons
                        $(':input[type="submit"]').prop('disabled', true);
                        if ($(this).closest('form').find('input.invalid:visible').length > 0) {
                            $(this).closest('form').find('input.invalid:visible')[0].focus();
                            //enable all submit buttons
                            $(':input[type="submit"]').prop('disabled', false);
                            event.preventDefault();
                            return false;
                        }


                        if ($J(this).find("#nocaptcha").length > 0 && $J(this).find("#nocaptcha").val() === "yes") {
                            return true;
                        }
                        if (grecaptcha) {
                            var v = grecaptcha.getResponse();
                            if (v.length == 0) {
                                event.preventDefault();
                                $J(".g-recaptcha").focus();
                                $J(".error.recaptcha").html("You can't leave Captcha Code empty");
                                //enable all submit buttons
                                $(':input[type="submit"]').prop('disabled', false);
                                return false;
                            }
                        }
                        return true;
                    }
                    catch (ex) {
                        if (typeof grecaptcha !== "undefined" && r.message != "grecaptcha is not defined") {
                            //enable all submit buttons
                            $(':input[type="submit"]').prop('disabled', false);
                            return false;
                        }
                    }

                });
                $J('form[class*="form"] input[type="text"],form[class*="form"] input[type="number"],form[class*="form"] textarea, form[class*="form"] input[type="email"]').each(function () {

                    if ($J(this).hasClass("alphabetswithspace")) {
                        $J(this).on('keyup keypress blur change', function () {
                            $J(this).parent().find('.field-validation-valid').text('');
                            $J(this).removeClass('invalid');
                            formValidations.validateText($(this));
                        });
                    }
                    if ($J(this).hasClass("postcode")) {
                        $J(this).on('keyup keypress blur change', function () {
                            $J(this).parent().find('.field-validation-valid').text('');
                            $J(this).removeClass('invalid');
                            formValidations.validatePostalCode($(this));
                        });
                    }
                    if ($J(this).hasClass("phonenumber")) {
                        $J(this).on('keyup keypress blur change', function () {
                            $J(this).parent().find('.field-validation-valid').text('');
                            $J(this).removeClass('invalid');
                            formValidations.validatePhoneNumber($(this));
                        });
                    }
                    if ($J(this).prop("type") == "email") {
                        $J(this).on('keyup keypress blur change', function () {
                            $J(this).parent().find('.field-validation-valid').text('');
                            $J(this).removeClass('invalid');
                            formValidations.validateEmail($(this));
                            if (!$J(this).hasClass("invalid")) {
                                try {
                                    $J(this)[0].setCustomValidity('')
                                } catch (e) { }
                            }
                            else {
                                $J(this)[0].setCustomValidity('Please enter valid email');
                            }
                        });

                    }
                    if ($J(this).hasClass("numbersonly")) {
                        $J(this).on('keyup keypress blur change', function () {
                            $J(this).parent().find('.field-validation-valid').text('');
                            $J(this).removeClass('invalid');
                            formValidations.validateNumbersOnly($(this));
                        });

                    }
                    if ($J(this).hasClass("alphanumericsOnly")) {
                        $J(this).on('keyup keypress blur change', function () {
                            $J(this).parent().find('.field-validation-valid').text('');
                            $J(this).removeClass('invalid');
                            formValidations.validateAlphanumericOnly($(this));
                        });

                    }

                });

                $J("form[class*='form']").find(".upload").on("change", function () {
                    var fileSize = $J(this)[0].files[0].size / 1048576;
                    if (fileSize > 5) {
                        $J(this).closest(".file").next('.field-validation-valid').text("Maximum file size allowed is 5mb.");
                        $J(this).closest(".file").next('.field-validation-valid').attr("exceedsize", "1");
                        $J(this).parent().find(".after").html("Click here to upload file.");
                        $J(this).replaceWith($J(this).val("").clone(true));
                    }
                    $J(this).closest(".file").next('.field-validation-valid').text("");
                    $J(this).closest(".file").next('.field-validation-valid').removeAttr("exceedsize");
                });

                $('#imageContainer').delegate(".bynderupload", "change", function () {
                    var imagesize = $J("#BynderImageSize") != undefined ? parseInt($J("#BynderImageSize").val()) : 10;
                    var fileSize = $J(this)[0].files[0].size / 1048576;
                    $J(this).parent().find(".after").html($J(this).val().substring($J(this).val().lastIndexOf("\\") + 1));
                    if (fileSize > imagesize) {
                        $J(this).parent().find(".after").html("");
                        $J(this).replaceWith($J(this).val("").clone(true));
                    }
                });
                if ($J("#operating-system") != undefined) {
                    $J("#operating-system").val(detectOperatingSystemName());
                }

                /*Relocation Form Date picker*/
                var relocationForm = $J("form[class='form-relocation-form']");
                if ($J(relocationForm) && $J(relocationForm).length > 0) {
                    var dateToday = new Date();
                    var newdate = new Date(dateToday);
                    newdate.setDate(newdate.getDate() + 5);
                    $J(relocationForm).find("#datepicker").datepicker('destroy');
                    $J(relocationForm).find("#datepicker").removeClass('hasDatepicker');
                    $J(relocationForm).find("#datepicker").datepicker({
                        showOn: "both",
                        buttonImage: "/images/svg/icon-datepicker.svg",
                        buttonImageOnly: !0,
                        buttonText: "Select date",
                        dateFormat: "dd/mm/yy",
                        minDate: newdate
                    });

                }
                /*Relocation Form Date picker*/

                /*Instagram Yearbook */

                if ($J("form[class='form-Instagram-Yearbook']").length > 0) {

                    var IGCameras = [];
                    var IGLens = [];
                    var IGSpeedliteFlashes = [];
                    var IGISO = [];
                    var IGAperture = [];
                    var IGShutterSpeed = [];
                    var $JInstagramProducts = $.get("/content/search/GetInstagramProducts", null, function (data) {
                        IGCameras = jQuery.map(data.Cameras, function (n, i) {
                            return n.SitecoreDisplayName.trim() == '' ? n.SitecoreItemName : n.SitecoreDisplayName.trim();
                        });;
                        IGLens = jQuery.map(data.Lenses, function (n, i) {
                            return n.SitecoreDisplayName.trim() == '' ? n.SitecoreItemName : n.SitecoreDisplayName.trim();
                        });
                        IGSpeedliteFlashes = jQuery.map(data.SpeedliteFlashes, function (n, i) {
                            return n.SitecoreDisplayName.trim() == '' ? n.SitecoreItemName : n.SitecoreDisplayName.trim();
                        });
                        IGISO = data.ISO;
                        IGAperture = data.Aperture;
                        IGShutterSpeed = data.ShutterSpeed;
                        if ($J("div[class='image-form'][data-index='0'").length == 0) {
                            $JInstagramProducts;
                            $('#btnAddNewImage').trigger("click");
                            //$J('.btn-remove-image[data-index="0"]').remove();
                        }
                        $J('.btn-remove-image[data-index="0"]').remove();

                        $J("div[class='image-form']").each(function (index, item) {
                            $('#imageContainer').find('.image-form[data-index="' + index + '"] .product-model-search-box').each(function (indx, item) {
                                var type = $(this).data("producttype");
                                if ($(this).typeahead().length > 0) {
                                    $(this).typeahead('destroy');
                                }
                                $(this).typeahead({
                                    source: $.debounce(function (query, process) {
                                        typeaheadSource(query, process, type);
                                    },300),
                                    minLength: 1,
                                    items: "8"
                                });

                            });
                            $('#imageContainer').find('.image-form[data-index="' + index + '"] select').each(function (indx, item) {
                                var type = $(this).data("droptype");
                                var $this = $(this);
                                var $selecteVal = $(this).val();
                                $this.empty();
                                switch (type) {
                                    case "IG-ISO":
                                        {
                                            $this.append($("<option></option>")
                                                .attr("value", "")
                                                .attr("selected", true)
                                                .text("Please select ISO"));
                                            $.each(IGISO, function (index, value) {

                                                if (value == $selecteVal) {
                                                    $this.append($("<option></option>")
                                                        .attr("value", value)
                                                        .attr("selected", true)
                                                        .text(value));
                                                }
                                                else {
                                                    $this.append($("<option></option>")
                                                        .attr("value", value)
                                                        .text(value));

                                                }
                                            });
                                            break;
                                        }
                                    case "IG-Aperture":
                                        {
                                            $this.append($("<option></option>")
                                                .attr("value", "")
                                                .attr("selected", true)
                                                .text("Please select Aperture"));
                                            $.each(IGAperture, function (index, value) {
                                                if (value == $selecteVal) {
                                                    $this.append($("<option></option>")
                                                        .attr("value", value)
                                                        .attr("selected", true)
                                                        .text(value));
                                                }
                                                else {
                                                    $this.append($("<option></option>")
                                                        .attr("value", value)
                                                        .text(value));

                                                }
                                            });
                                            break;
                                        }
                                    case "IG-ShutterSpeed":
                                        {
                                            $this.append($("<option></option>")
                                                .attr("value", "")
                                                .attr("selected", true)
                                                .text("Please select ShutterSpeed"));
                                            $.each(IGShutterSpeed, function (index, value) {
                                                if (value == $selecteVal) {
                                                    $this.append($("<option></option>")
                                                        .attr("value", value)
                                                        .attr("selected", true)
                                                        .text(value));
                                                }
                                                else {
                                                    $this.append($("<option></option>")
                                                        .attr("value", value)
                                                        .text(value));

                                                }
                                            });
                                            break;
                                        }
                                    default:
                                        break;
                                }


                            });
                        });
                    });

                    // Add New Image
                    $('#btnAddNewImage').click(function () {

                        // Clone template
                        var newImageContent = $('#templateImage').clone();
                        // new address index. Need to exclude template
                        var imageIndex = $('.image-form').length - 1;
                        // assign image property name
                        $(newImageContent).find('.image-field').each(function (ind) {
                            var newName = $(this).attr('name').replace('TemplateImage.', 'InstagramImages[' + imageIndex + '].');
                            $(this).attr('name', newName);
                            if ($(this).hasClass("mandatory")) {
                                $(this).attr('required', 'true');
                            }
                            $(this)[0].id = $(this)[0].id.replace('TemplateImage.', 'InstagramImages[' + imageIndex + '].');


                        });
                        $(newImageContent).find('.image-field-validation').each(function (ind) {
                            var newName = $(this).attr('data-valmsg-for').replace('TemplateImage.', 'InstagramImages[' + imageIndex + '].');
                            $(this).attr('data-valmsg-for', newName);
                        });
                        // assign data-index
                        $(newImageContent).find('[data-index]').each(function () { $(this).attr('data-index', imageIndex) });

                        // assign data-propertyname
                        $(newImageContent).find('[data-propertyname]').each(function () { $(this).attr('data-propertyname', 'InstagramImages[' + imageIndex + '].') });
                        // append new image form
                        $('#imageContainer').append($(newImageContent).html());
                        // reset form validation

                        $('#imageContainer').find('.image-form[data-index="' + imageIndex + '"] .product-model-search-box').each(function (indx, item) {
                            var type = $(this).data("producttype");
                            $(this).typeahead({
                                source: $.debounce(function (query, process) {
                                    typeaheadSource(query, process, type);
                                },300),
                                minLength: 1,
                                items: "8"
                            });

                        });
                        $('#imageContainer').find('.image-form[data-index="' + imageIndex + '"] select').each(function (indx, item) {
                            var type = $(this).data("droptype");
                            var $this = $(this);
                            switch (type) {
                                case "IG-ISO":
                                    {
                                        $.each(IGISO, function (index, value) {
                                            $this.append($("<option></option>")
                                                .attr("value", value)
                                                .text(value));
                                        });
                                        break;
                                    }
                                case "IG-Aperture":
                                    {
                                        $.each(IGAperture, function (index, value) {
                                            $this.append($("<option></option>")
                                                .attr("value", value)
                                                .text(value));
                                        });
                                        break;
                                    }
                                case "IG-ShutterSpeed":
                                    {
                                        $.each(IGShutterSpeed, function (index, value) {
                                            $this.append($("<option></option>")
                                                .attr("value", value)
                                                .text(value));
                                        });
                                        break;
                                    }
                                default:
                                    break;
                            }


                        });
                        $('#imageContainer').find('.image-form[data-index="' + imageIndex + '"]').delegate(".dpicker", "focusin", function () {
                            var $this = $(this);
                            if (!$this.data('datepicker')) {
                                $this.removeClass("hasDatepicker").removeAttr('id');
                                $this.datepicker("destroy");
                                $this.parent().find('img.ui-datepicker-trigger').remove();
                                $this.datepicker({ showOn: "both", buttonImage: "/images/svg/icon-datepicker.svg", buttonImageOnly: !0, buttonText: "Select date", dateFormat: "dd/mm/yy", maxDate: "0" });
                            }

                        });

                        return false;
                    });

                    function typeaheadSource(query, response, type) {
                        // This is going to make an HTTP post request to the controller3
                        canonHelper.showSpinner();

                        if (IGCameras.length == 0 || IGLens.length == 0) {
                            $JInstagramProducts;
                        }
                        if (type == "Camera") {
                            canonHelper.hideSpinner();
                            return response(IGCameras)
                        }
                        else if (type == "lens") {
                            canonHelper.hideSpinner();
                            return response(IGLens)
                        }
                        else if (type == "speedliteflashes") {
                            canonHelper.hideSpinner();
                            return response(IGSpeedliteFlashes)
                        }


                        return null;
                    }

                    var spinnerVisible = false;

                    function showProgress() {
                        if (!spinnerVisible) {
                            $("div#spinner").fadeIn("fast");
                            $(".image-spinner").html("Loading");
                            spinnerVisible = true;
                        }
                    };

                    function hideProgress() {
                        if (spinnerVisible) {
                            var spinner = $("div#spinner");
                            spinner.stop();
                            spinner.fadeOut("fast");
                            spinnerVisible = false;
                        }
                    };
                    // Delete Image
                    $('#imageContainer').delegate('.btn-remove-image', 'click', function () {
                        var index = $(this).attr('data-index');
                        $('.image-form').each(function () {
                            var $form = $(this);
                            if (index == $form.attr('data-index')) {
                                var $imageId = $form.find('.image-id');
                                var $imageRemoved = $form.find('.image-removed');
                                var id = $imageId.val();
                                $imageRemoved.val('true');
                                if (id > 0) {
                                    $form.addClass('image-deleted');
                                } else {
                                    $form.hide();
                                    $form.find('.image-field').each(function (ind) {
                                        if ($(this).hasClass("mandatory")) {
                                            $(this).removeAttr('required');
                                        }

                                    });
                                }
                            }
                        });

                        return false;
                    });
                }
                /*Instagram Yearbook */
                /*Consumer support*/
                if ($J("#accessories-include") != undefined) {
                    $J(".accessories-desc").hide();
                    $J("#accessories").removeAttr("required");
                    $J("#accessories-include").change(function () {
                        if ($J("#accessories-include option:selected").val().toLowerCase() === "yes") {
                            $J(".accessories-desc").show();
                            $J("#accessories").attr("required", "true");

                            $J("#accessories").before("<span class='mandatory-check'>*</span>").addClass('mandatory-field-text');
                        }
                        else {
                            $J(".accessories-desc").hide();
                            $J("#accessories").removeAttr("required");

                            $J("#accessories").removeClass('mandatory-field-text');
                            $J(".accessories-desc").find('.mandatory-check').remove();
                        }
                    });
                }
                if ($J("#warranty") != undefined) {
                    $J(".proof-of-purchase").hide();
                    $J(".date-of-purchase").hide();
                    $J("#receipt").removeAttr("required");
                    $J("#nzdatepicker").removeAttr("required");
                    $J("#warranty").change(function () {
                        if ($J("#warranty option:selected").val().toLowerCase() === "yes") {
                            $J(".proof-of-purchase").show();
                            $J("#receipt").attr("required", "true");
                            //Requested by NZ Camera Service Team - NZ Consumer Form datapicker only appears when Warranty option is yes
                            $J("#nzdatepicker").attr("required", "true");
                            //RITM0146382 - Requested by NZ Camera Service Team - NZ Consumer Form Pre-Approved repair cost only appears when Warranty option is not yes
                            $J(".pre-approved-repair-cost").hide();
                            $J("#repair-cost").removeAttr("required");
                            $('.proof-of-purchase').find('.file').before("<span class='mandatory-check'>*</span>").addClass('mandatory-field-text');

                            $J(".date-of-purchase").show();
                            $('.date-of-purchase').find('input').attr('required', true).before("<span class='mandatory-check'>*</span>").addClass('mandatory-field-text');

                        }
                        else {
                            $J(".proof-of-purchase").hide();
                            $J("#receipt").removeAttr("required");
                            //Requested by NZ Camera Service Team - NZ Consumer Form datapicker only appears when Warranty option is yes
                            $J("#nzdatepicker").removeAttr("required");
                            //RITM0146382 - Requested by NZ Camera Service Team - NZ Consumer Form Pre-Approved repair cost only appears when Warranty option is not yes
                            $J(".pre-approved-repair-cost").show();
                            $J("#repair-cost").attr("required", "true");

                            $('.proof-of-purchase').find(".mandatory-check").remove();
                            $('.proof-of-purchase').find(".file").removeClass('mandatory-field-text');

                            $J(".date-of-purchase").hide();
                            $('.date-of-purchase').find('input').removeAttr('required').removeClass('mandatory-field-text');
                            $('.date-of-purchase').find(".mandatory-check").remove();
                        }
                    });
                }
                /*NZ consumer support*/
                if ($J("#repair-cost") != undefined) {
                    $J("#repair-cost-message").hide();
                    $J("#repair-cost").change(function () {
                        if ($J("#repair-cost option:selected").val().toLowerCase().startsWith("estimate of repair required")) {
                            $J("#repair-cost-message").show();
                        }
                        else {
                            $J("#repair-cost-message").hide();
                        }
                    });
                }

                /*Order Toner form*/
                $J(".shipping-address-section").hide();
                $J("#IsShippingAddress-yes, #IsShippingAddress-no").click(function () {
                    if ($J(this).val().toLowerCase() === "yes") {
                        $J(".shipping-address-section").show();
                        $J(".shipping-address-section").find("[mandatory]").attr("required", "true");
                    }
                    else {
                        $J(".shipping-address-section").hide();
                        $J(".shipping-address-section").find("[mandatory]").removeAttr("required");
                    }
                });

                /*Contant conon form*/
                $J(".contact-form-contact-method").hide();
                $J(".contact-form-primary-number").on("keyup", function (e) {
                    if ($J(this).val() !== "") {
                        $J(".contact-form-contact-method").show();
                        $J(".contact-form-contact-method").find("[mandatory]").attr("required", "true");
                    }
                    else {
                        $J(".contact-form-contact-method").hide();
                        $J(".contact-form-contact-method").find("[mandatory]").removeAttr("required");
                    }
                });

                /*Business enquiry form*/
                $J(".business-enquiry-form-contact-method").hide();
                $J(".business-enquiry-form-primary-number").on("keyup", function (e) {
                    if ($J(this).val() !== "") {
                        $J(".business-enquiry-form-contact-method").show();
                    }
                    else {
                        $J(".business-enquiry-form-contact-method").hide();
                    }
                });


                $J(".oss-purchase").hide();
                $J("#PurchasedOnSite-yes, #PurchasedOnSite-no").click(function () {
                    if ($J(this).val().toLowerCase() === "yes") {
                        $J(".oss-purchase").show();
                    }
                    else {
                        $J(".oss-purchase").hide();
                    }
                });

                $J(".support-call").hide();
                $J("#MakeServiceOrSupportCall-yes, #MakeServiceOrSupportCall-no").click(function () {
                    if ($J(this).val().toLowerCase() === "yes") {
                        $J(".support-call").show();
                    }
                    else {
                        $J(".support-call").hide();
                    }
                });

                $J(".warranty-abn").hide();
                $J(".warranty-company-name").on("keyup", function (e) {
                    if ($J(this).val() != "") {
                        $J(".warranty-abn").show();
                    }
                    else {
                        $J(".warranty-abn").hide();
                    }
                });

                $J(".mdsField").hide();
                $J("#IsMdsCustomer-yes, #IsMdsCustomer-no").click(function () {
                    if ($J(this).val().toLowerCase() === "yes") {
                        $J(".mdsField").show();
                        $J(".mdsField").find("[mandatory]").attr("required", "true");

                    }
                    else {
                        $J(".mdsField").hide();
                        $J(".mdsField").find("[mandatory]").removeAttr("required");
                    }
                });

                $J(".moving-to-location-diff").hide();
                $J("#ismovinglocdiff-yes, #ismovinglocdiff-no").click(function () {
                    if ($J(this).val().toLowerCase() === "yes") {
                        $J(".moving-to-location-diff").show();
                        $J(".moving-to-location-diff").find("[mandatory]").attr("required", "true");
                    }
                    else {
                        $J(".moving-to-location-diff").hide();
                        $J(".moving-to-location-diff").find("[mandatory]").removeAttr("required");
                    }
                });

                $J(".relocate-more-machines").show();
                $J(".relocate-more-machines").find("[mandatory]").attr("required", "true");
                $J(".diff-moving-to-address").hide();
                $J(".diff-moving-to-address").find("[mandatory]").removeAttr("required");
                $J(".moving-to-location-diff").hide();
                $J(".moving-to-location-diff").find("[mandatory]").removeAttr("required");
                $J("#ismoremachines-yes, #ismoremachines-no").click(function () {
                    if ($J(this).val().toLowerCase() === "no") {
                        $J(".relocate-more-machines").show();
                        $J(".relocate-more-machines").find("[mandatory]").attr("required", "true");
                        $J(".diff-moving-to-address").hide();
                        $J(".diff-moving-to-address").find("[mandatory]").removeAttr("required");
                        $J(".moving-to-location-diff").hide();
                        $J(".moving-to-location-diff").find("[mandatory]").removeAttr("required");
                    }
                    else {
                        $J(".relocate-more-machines").hide();
                        $J(".relocate-more-machines").find("[mandatory]").removeAttr("required");
                        $J(".diff-moving-to-address").hide();
                        $J(".diff-moving-to-address").find("[mandatory]").removeAttr("required");
                        $J(".moving-to-location-diff").hide();
                        $J(".moving-to-location-diff").find("[mandatory]").removeAttr("required");
                    }
                });

                if ($J(".additional-access-info").length > 0) {
                    $J(".additional-access-info").change(function () {
                        if ($(this).prop("checked")) {
                            $J(".additional-access-info").removeAttr("required");
                        }
                        else {
                            var anySelected = false;
                            $J(".additional-access-info").each(function () {
                                if ($J(this).prop("checked")) {
                                    anySelected = true;
                                }
                            });
                            if (!anySelected) {
                                $J(".additional-access-info").attr("required", "true");
                            }
                        }
                    });
                }

                $J(".from-stairs").hide();
                $J("#from-AccessToSite").change(function () {
                    var $val = $J(this).find(":selected").val();
                    if ($val.toLowerCase() === "stairs") {
                        $J(".from-stairs").show();
                        $J(".from-manoeuvre").hide();
                        $J(".from-stairs").find("[mandatory]").attr("required", "true");
                        $J(".from-manoeuvre").find("[mandatory]").attr("required", "true");
                        $J("#from-isStaircaseHaveLanding-yes, #from-isStaircaseHaveLanding-no").click();
                    }
                    else {
                        $J(".from-stairs").hide();
                        $J(".from-manoeuvre").hide();
                        $J(".from-stairs").find("[mandatory]").removeAttr("required");
                        $J(".from-manoeuvre").find("[mandatory]").removeAttr("required");
                    }
                });

                $J(".to-stairs").hide();
                $J("#to-AccessToSite").change(function () {
                    var $val = $J(this).find(":selected").val();
                    if ($val.toLowerCase() === "stairs") {
                        $J(".to-stairs").show();
                        $J(".to-manoeuvre").hide();
                        $J(".to-stairs").find("[mandatory]").attr("required", "true");
                        $J(".to-manoeuvre").find("[mandatory]").attr("required", "true");
                    }
                    else {
                        $J(".to-stairs").hide();
                        $J(".to-manoeuvre").hide();
                        $J(".to-stairs").find("[mandatory]").removeAttr("required");
                        $J(".to-manoeuvre").find("[mandatory]").removeAttr("required");
                    }
                });

                $J(".from-manoeuvre").hide();
                $J("#from-isStaircaseHaveLanding-yes, #from-isStaircaseHaveLanding-no").click(function () {
                    if ($J(this).val().toLowerCase() === "yes") {
                        $J(".from-manoeuvre").show();
                        $J(".from-manoeuvre").find("[mandatory]").attr("required", "true");
                    }
                    else {
                        $J(".from-manoeuvre").hide();
                        $J(".from-manoeuvre").find("[mandatory]").removeAttr("required");
                    }
                });

                $J(".to-manoeuvre").hide();
                $J("#to-isStaircaseHaveLanding-yes, #to-isStaircaseHaveLanding-no").click(function () {
                    if ($J(this).val().toLowerCase() === "yes") {
                        $J(".to-manoeuvre").show();
                        $J(".to-manoeuvre").find("[mandatory]").attr("required", "true");
                    }
                    else {
                        $J(".to-manoeuvre").hide();
                        $J(".to-manoeuvre").find("[mandatory]").removeAttr("required");
                    }
                });

                $J(".diff-moving-to-address").hide();
                $J("#IsSameMovingToAddress-yes, #IsSameMovingToAddress-no").click(function () {
                    if ($J(this).val().toLowerCase() === "no") {
                        $J(".diff-moving-to-address").show();
                        $J(".diff-moving-to-address").find("[mandatory]").attr("required", "true");
                        $J(".to-stairs").hide();
                        $J(".to-manoeuvre").hide();
                    }
                    else {
                        $J(".diff-moving-to-address").hide();
                        $J(".diff-moving-to-address").find("[mandatory]").removeAttr("required");
                        $J(".to-stairs").hide();
                        $J(".to-manoeuvre").hide();
                    }
                });

                var addNewMachineRows = function addRow(field) {
                    var index = parseInt($J(".add-more-device").data("noofdevices")) + 1;
                    if (index < 10) {
                        $J(".add-more-device").data("noofdevices", index);
                        //copy the table row and clear the value of the input, then append the row to the end of the table
                        $("." + field + " .field:first").clone().find("input").each(function () {
                            $(this).val("");
                            $(this).attr("id", $(this).attr("id") + index);
                        }).end().appendTo("." + field);

                        $("." + field + " .field:nth-child(2)").clone().find("input").each(function () {
                            $(this).val("");
                            $(this).attr("id", $(this).attr("id") + index);
                        }).end().appendTo("." + field);

                        $("." + field + " .field:nth-child(3)").clone().find("a").each(function () {
                            $(this).attr("id", $(this).attr("id") + index);
                            $(this).show();
                            $(this).click(function () {
                                var counter = $J(".add-more-device").data("noofdevices");
                                $J(".add-more-device").data("noofdevices", counter - 1);
                                $(".devices .field").find("#product-name" + index).parent().remove();
                                $(".devices .field").find("#product-serial" + index).parent().remove();
                                $(".devices .field").find("#remove-device" + index).parent().remove();
                            });
                        }).end().appendTo("." + field);
                    }
                }

                if ($J(".add-more-device").length > 0) {
                    $(".devices .field .remove-more-device").hide();
                    $J(".add-more-device").click(function () {
                        addNewMachineRows("devices");
                    });
                }

                //Donation form
                if ($J(".sponsorshipdate").length > 0) {
                    $J(".sponsorshipdate").removeClass("hasDatepicker").removeAttr('id');
                    $J(".sponsorshipdate").datepicker("destroy");
                    $J(".sponsorshipdate").parent().find('img.ui-datepicker-trigger').remove();
                    $J(".sponsorshipdate").datepicker({ showOn: "both", buttonImage: "/images/svg/icon-datepicker.svg", buttonImageOnly: !0, buttonText: "Select date", dateFormat: "dd/mm/yy", minDate: "0", maxDate: null });
                }

                //CPS form
                var showHideCPSMeberNumber = function (show) {
                    var cpsMebershipNumberArea = $J(".show-hide-cps");
                    if (show) {
                        cpsMebershipNumberArea.show();
                        cpsMebershipNumberArea.find("[mandatory]").attr("required", "true");
                        cpsMebershipNumberArea.find("[mandatory]").before("<span class='mandatory-check'>*</span>").addClass('mandatory-field-text');
                    }
                    else {
                        cpsMebershipNumberArea.find("[mandatory]").removeAttr("required");
                        cpsMebershipNumberArea.hide();
                        cpsMebershipNumberArea.find('.mandatory-check').remove();
                        cpsMebershipNumberArea.find("[mandatory]").removeClass('mandatory-field-text');
                    }
                }


                showHideCPSMeberNumber(false);


                $J('input#cps-member').click(function () {
                    if ($(this).is(':checked')) {
                        showHideCPSMeberNumber(true);
                    }
                    else {
                        showHideCPSMeberNumber(false);
                    }
                });

                if ($('.form-service-repair.revised').length > 0) {
                    $('[required][type="text"],[required][type="number"],[required][type="email"]').before("<span class='mandatory-check'>*</span>").addClass('mandatory-field-text');
                    $('[required][type="file"]').parent('.file').before("<span class='mandatory-check mandatory-field-text'>*</span>");
                    $('select[required]').parent('.dropdown').before("<span class='mandatory-check'>*</span>").addClass('mandatory-field-dropdown');
                    $('select[required]').closest(".row").parent('.dropdown').before("<span class='mandatory-check'>*</span>").addClass('mandatory-field-dropdown-col');
                }


            },

            initLoadNZFormProductData: function () {
                var contentsSource = {};
                var $scope = $J('form.nz-consumer-service-repair-form');

                if ($scope && $scope.length > 0) {
                    applyEventBindings($scope);
                    loadRemoteData($scope);
                    configureTypeAhead($scope);
                }

                function loadRemoteData($scope) {
                    if ($scope.context == undefined) {
                        return;
                    }

                    //var request = $.get('/js/nz-consumer-form/productdata.json', {});
                    var request = $.get('/support/loadrepairableproductdata', {});

                    request.done(function (data) {
                        if (data != undefined) {
                            if (data.Data.ProductCategories != undefined) {
                                contentsSource = data.Data;
                                //filterNZFormProducts();
                                bindDropDowns($scope, data.Data, true);
                            }
                        }
                    });
                }

                function filterNZFormProducts() {
                    //for (var i = contentsSource.ProductCategories.length - 1; i >= 0; i--) {
                    //    if ((contentsSource.ProductCategories[i].SitecoreItemName !== "Cameras") && (contentsSource.ProductCategories[i].SitecoreItemName !== "Camera Lenses") && (contentsSource.ProductCategories[i].SitecoreItemName !== "Printers") && (contentsSource.ProductCategories[i].SitecoreItemName !== "Other Products") && (contentsSource.ProductCategories[i].SitecoreItemName !== "Accessories Supplies")) {
                    //        contentsSource.ProductCategories.splice(i, 1);
                    //    }
                    //    else if (contentsSource.ProductCategories[i].SitecoreItemName === "Printers") {
                    //        for (var j = contentsSource.ProductCategories[i].SubCategories.length - 1; j >= 0; j--) {
                    //            if ((contentsSource.ProductCategories[i].SubCategories[j].SitecoreItemName !== "Home Printers") && (contentsSource.ProductCategories[i].SubCategories[j].SitecoreItemName !== "Professional Printers")) {
                    //                contentsSource.ProductCategories[i].SubCategories.splice(j, 1);
                    //            }
                    //        }
                    //    }
                    //    else if (contentsSource.ProductCategories[i].SitecoreItemName === "Other Products") {
                    //        for (var k = contentsSource.ProductCategories[i].SubCategories.length - 1; k >= 0; k--) {
                    //            if ((contentsSource.ProductCategories[i].SubCategories[k].SitecoreItemName !== "Projectors") && (contentsSource.ProductCategories[i].SubCategories[k].SitecoreItemName !== "Scanners") && (contentsSource.ProductCategories[i].SubCategories[k].SitecoreItemName !== "Calculators")) {
                    //                contentsSource.ProductCategories[i].SubCategories.splice(k, 1);
                    //            }
                    //        }
                    //    }
                    //    else if (contentsSource.ProductCategories[i].SitecoreItemName === "Accessories Supplies") {
                    //        for (var l = contentsSource.ProductCategories[i].SubCategories.length - 1; l >= 0; l--) {
                    //            if ((contentsSource.ProductCategories[i].SubCategories[l].SitecoreItemName !== "Speedlite Flashes") && (contentsSource.ProductCategories[i].SubCategories[l].SitecoreItemName !== "Lens Adapters") && (contentsSource.ProductCategories[i].SubCategories[l].SitecoreItemName !== "Lens Extenders") && (contentsSource.ProductCategories[i].SubCategories[l].SitecoreItemName !== "Microphones")) {
                    //                contentsSource.ProductCategories[i].SubCategories.splice(l, 1);
                    //            }
                    //        }
                    //    }
                    //}

                    for (var i = contentsSource.ProductCategories.length - 1; i >= 0; i--) {
                        for (var j = contentsSource.ProductCategories[i].SubCategories.length - 1; j >= 0; j--) {
                            for (var k = contentsSource.ProductCategories[i].SubCategories[j].Products.length - 1; k >= 0; k--) {
                                if (contentsSource.ProductCategories[i].SubCategories[j].Products[k].Repairable !== true) {
                                    contentsSource.ProductCategories[i].SubCategories[j].Products.splice(k, 1);
                                }
                                else if (contentsSource.ProductCategories[i].SubCategories[j].Products[k].SitecoreItemName === "support") {
                                    contentsSource.ProductCategories[i].SubCategories[j].Products.splice(k, 1);
                                }
                            }
                            if (contentsSource.ProductCategories[i].SubCategories[j].Products.length === 0) {
                                contentsSource.ProductCategories[i].SubCategories.splice(j, 1);
                            }
                        }
                        if (contentsSource.ProductCategories[i].SubCategories.length === 0) {
                            contentsSource.ProductCategories.splice(i, 1);
                        }
                    }
                    //console.log(contentsSource);
                }

                function searchProducts(filterString, response) {
                    var filteredResults = [];

                    for (var i = contentsSource.ProductCategories.length - 1; i >= 0; i--) {
                        for (var j = contentsSource.ProductCategories[i].SubCategories.length - 1; j >= 0; j--) {
                            for (var k = contentsSource.ProductCategories[i].SubCategories[j].Products.length - 1; k >= 0; k--) {
                                if (contentsSource.ProductCategories[i].SubCategories[j].Products[k].SitecoreItemName.toLowerCase().includes(filterString.toLowerCase())) {
                                    filteredResults.push({
                                        'Category': contentsSource.ProductCategories[i].SitecoreItemName,
                                        'CategoryItemId': contentsSource.ProductCategories[i].SitecoreItemId,
                                        'Subcategory': contentsSource.ProductCategories[i].SubCategories[j].SitecoreItemName,
                                        'SubcategoryItemId': contentsSource.ProductCategories[i].SubCategories[j].SitecoreItemId,
                                        'name': contentsSource.ProductCategories[i].SubCategories[j].Products[k].Heading,
                                        'ModelItemId': contentsSource.ProductCategories[i].SubCategories[j].Products[k].SitecoreItemId,
                                        'ModelItemName': contentsSource.ProductCategories[i].SubCategories[j].Products[k].SitecoreItemName
                                    })
                                }
                            }
                        }
                    }
                    response(filteredResults)
                }

                function bindDropDowns($scope, data, isPageLoad) {
                    var ddlProductCategories = $scope.find('#ddlProductCategories');
                    var ddlProductSubCategories = $scope.find('#ddlProductSubCategories');
                    var ddlProduct = $scope.find('#ddlProduct');

                    filterNZFormProducts();

                    if (isPageLoad) {
                        $J(ddlProductCategories).empty().append('<option selected="selected" value="">Select Category</option>');

                        var productCategoryCounter = 0;
                        var pc = sortResults("SitecoreItemName", true, data.ProductCategories);
                        $.each(pc, function () {
                            $J(ddlProductCategories).append($J("<option></option>").val(this['SitecoreItemId']).html(this['SitecoreItemName']));
                            productCategoryCounter++;
                        });

                        $J(ddlProductSubCategories).empty().append('<option selected="selected" value="">Select Subcategory</option>');
                        $J(ddlProduct).empty().append('<option selected="selected" value="" disabled="disabled">Select Model</option>');

                        var selectedProductCategory = $scope.find('#ProductCategoryId').val();
                        if (selectedProductCategory !== '00000000-0000-0000-0000-000000000000') {
                            $J(ddlProductCategories).val(selectedProductCategory).change();
                        }
                        else {
                            $J(ddlProductCategories).val('').change();
                        }

                        var selectedProductSubCategory = $scope.find('#ProductSubCategoryId').val();
                        if (selectedProductSubCategory !== '00000000-0000-0000-0000-000000000000') {
                            $J(ddlProductSubCategories).val(selectedProductSubCategory).change();
                        }
                        else {
                            $J(selectedProductSubCategory).val('').change();
                        }

                        var selectedProduct = $scope.find('#ProductId').val();
                        if (selectedProduct !== '00000000-0000-0000-0000-000000000000') {
                            $J(ddlProduct).val(selectedProduct).change();
                            if (selectedProductCategory === '00000000-0000-0000-0000-000000000000') {
                                $J(ddlProductSubCategories).val(selectedProductCategory).change();
                            }
                        }
                    }
                }

                function applyEventBindings($scope) {
                    $scope.off("change", "#ddlProductCategories");
                    $scope.on("change", "#ddlProductCategories", function () {
                        var $this = $J(this);
                        var ddlProductSubCategories = $J('#ddlProductSubCategories');
                        var ddlProduct = $J('#ddlProduct');
                        $J(ddlProductSubCategories).empty().append('<option selected="selected" value="">Select Subcategory</option>');
                        $J(ddlProduct).empty().append('<option selected="selected" value="" disabled="disabled">Select Model</option>');
                        if ($this.val() !== '' && $this.val() != null) {
                            var categories = contentsSource.ProductCategories.filter(function (q) {
                                return q.SitecoreItemId === $this.val();
                            });

                            $scope.find('#ProductCategoryId').val($this.val());

                            var pcs = sortResults("SitecoreItemName", true, categories[0].SubCategories);
                            $.each(pcs, function () {
                                $J(ddlProductSubCategories).append($J("<option></option>").val(this['SitecoreItemId']).html(this['SitecoreItemName']));
                            });

                        }
                        else {
                            $J(ddlProductSubCategories).val();
                            $J(ddlProduct).val('');
                        }

                    });

                    $scope.off("change", "#ddlProductSubCategories");
                    $scope.on("change", "#ddlProductSubCategories", function () {
                        var $this = $J(this);
                        var ddlProduct = $J('#ddlProduct');
                        $J(ddlProduct).empty().append('<option selected="selected" value="" disabled="disabled">Select Model</option>');
                        $J(".divproduct").show();
                        if ($this.val() !== '' && $this.val() != null) {
                            var categories = contentsSource.ProductCategories.filter(function (q) {
                                return q.SitecoreItemId === $J("#ddlProductCategories").val();
                            });

                            $scope.find('#ProductSubCategoryId').val($this.val());

                            var subCategories = categories[0].SubCategories.filter(function (q) {
                                return q.SitecoreItemId === $this.val();
                            });

                            if (subCategories[0].SitecoreTemplateId !== $J("#ProductTemplateId").val()) {
                                var prds = sortResults("SitecoreItemName", true, subCategories[0].Products);
                                $.each(prds, function () {
                                    $J(ddlProduct).append($J("<option></option>").attr('data-hashelpcontent', this['HasHelpContent']).val(this['SitecoreItemName']).html(this['Heading']));
                                });
                            } else {
                                $J(".divproduct").hide();
                                $J(ddlProduct).append($J("<option></option>").attr('data-hashelpcontent', this['HasHelpContent']).val(subCategories[0].SitecoreItemId).html(subCategories[0].SitecoreItemName));
                                $J(ddlProduct).val($this.val()).change();

                            }
                        }
                    });

                    $scope.off("change", "#ddlProduct");
                    $scope.on("change", "#ddlProduct", function () {
                        var $this = $J(this);
                        if ($this.val() !== '' && $this.val() != null) {
                            var hiddenPrinterCategoryProductId = $scope.find('#PrinterProductCategoryId').val();
                            var categoryId = $("#ddlProductCategories option:selected").val();
                            if (categoryId.length === 0)
                                categoryId = "";

                            $scope.find('#ProductId').val($this.val());
                        }

                    });

                }

                function sortResults(prop, asc, items) {
                    items = items.sort(function (a, b) {
                        if (asc) {
                            return (a[prop] > b[prop]) ? 1 : ((a[prop] < b[prop]) ? -1 : 0);
                        } else {
                            return (b[prop] > a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0);
                        }
                    });

                    return items;
                }

                function configureTypeAhead($scope) {
                    if ($(".product-model-type-ahead").length > 0) {
                        $('body').delegate('.product-model-type-ahead', 'focus', function () {
                            $(".product-model-type-ahead").typeahead({
                                source: $.debounce(function (query, response) {
                                    searchProducts(query, response);
                                }, 300),
                                minLength: 2,
                                items: "8",
                                afterSelect: function (selectedItem) {
                                    console.log("selectedItem", selectedItem);
                                    var ddlProductCategories = $scope.find('#ddlProductCategories');
                                    var ddlProductSubCategories = $scope.find('#ddlProductSubCategories');
                                    var ddlProduct = $scope.find('#ddlProduct');
                                    $(ddlProductCategories).find(`option[value="${selectedItem.CategoryItemId}"]`).prop('selected', true).change();
                                    setTimeout(() => {
                                        $(ddlProductSubCategories).find(`option[value="${selectedItem.SubcategoryItemId}"]`).prop('selected', true).change();
                                        setTimeout(() => {
                                            $(ddlProduct).find(`option[value="${selectedItem.ModelItemName}"]`).prop('selected', true).change();
                                        }, 100)
                                    }, 100)
                                    $(".product-model-type-ahead").val("");
                                }
                            });
                        });
                    }
                }
            },            
            initLoadAUFormProductData: function () {
                var contentsSource = {};
                var $scope = $J('form.form-service-repair');

                if ($scope && $scope.length > 0) {
                    applyEventBindings($scope);
                    loadRemoteData($scope);
                    configureTypeAhead($scope);
                }

                function loadRemoteData($scope) {
                    if ($scope.context == undefined) {
                        return;
                    }

                    var request = $.get('/support/loadrepairableproductdata', {});

                    request.done(function (data) {
                        if (data != undefined) {
                            if (data.Data.ProductCategories != undefined) {
                                contentsSource = data.Data;
                                bindDropDowns($scope, data.Data, true);
                            }
                        }
                    });
                }

                function filterAUFormProducts() {
                    for (var i = contentsSource.ProductCategories.length - 1; i >= 0; i--) {
                        for (var j = contentsSource.ProductCategories[i].SubCategories.length - 1; j >= 0; j--) {
                            for (var k = contentsSource.ProductCategories[i].SubCategories[j].Products.length - 1; k >= 0; k--) {
                                if (contentsSource.ProductCategories[i].SubCategories[j].Products[k].Repairable !== true) {
                                    contentsSource.ProductCategories[i].SubCategories[j].Products.splice(k, 1);
                                }
                                else if (contentsSource.ProductCategories[i].SubCategories[j].Products[k].SitecoreItemName === "support") {
                                    contentsSource.ProductCategories[i].SubCategories[j].Products.splice(k, 1);
                                }
                            }
                            if (contentsSource.ProductCategories[i].SubCategories[j].Products.length === 0) {
                                contentsSource.ProductCategories[i].SubCategories.splice(j, 1);
                            }
                        }
                        if (contentsSource.ProductCategories[i].SubCategories.length === 0) {
                            contentsSource.ProductCategories.splice(i, 1);
                        }
                    }
                    console.log(contentsSource);
                }

                function searchProducts(filterString, response) {
                    var filteredResults = [];

                    for (var i = contentsSource.ProductCategories.length - 1; i >= 0; i--) {
                        for (var j = contentsSource.ProductCategories[i].SubCategories.length - 1; j >= 0; j--) {
                            for (var k = contentsSource.ProductCategories[i].SubCategories[j].Products.length - 1; k >= 0; k--) {
                                if (contentsSource.ProductCategories[i].SubCategories[j].Products[k].SitecoreItemName.toLowerCase().includes(filterString.toLowerCase())) {
                                    filteredResults.push({
                                        'Category': contentsSource.ProductCategories[i].SitecoreItemName,
                                        'CategoryItemId': contentsSource.ProductCategories[i].SitecoreItemId,
                                        'Subcategory': contentsSource.ProductCategories[i].SubCategories[j].SitecoreItemName,
                                        'SubcategoryItemId': contentsSource.ProductCategories[i].SubCategories[j].SitecoreItemId,
                                        'name': contentsSource.ProductCategories[i].SubCategories[j].Products[k].Heading,
                                        'ModelItemId': contentsSource.ProductCategories[i].SubCategories[j].Products[k].SitecoreItemId,
                                        'ModelItemName': contentsSource.ProductCategories[i].SubCategories[j].Products[k].SitecoreItemName
                                    })
                                }
                            }
                        }
                    }
                    response(filteredResults)
                }

                function bindDropDowns($scope, data, isPageLoad) {
                    var ddlProductCategories = $scope.find('#ddlProductCategories');
                    var ddlProductSubCategories = $scope.find('#ddlProductSubCategories');
                    var ddlProduct = $scope.find('#ddlProduct');

                    filterAUFormProducts();

                    if (isPageLoad) {
                        $J(ddlProductCategories).empty().append('<option selected="selected" value="">Select Category</option>');

                        var productCategoryCounter = 0;
                        var pc = sortResults("SitecoreItemName", true, data.ProductCategories);
                        $.each(pc, function () {
                            $J(ddlProductCategories).append($J("<option></option>").val(this['SitecoreItemId']).html(this['SitecoreItemName']));
                            productCategoryCounter++;
                        });

                        $J(ddlProductSubCategories).empty().append('<option selected="selected" value="">Select Subcategory</option>');
                        $J(ddlProduct).empty().append('<option selected="selected" value="" disabled="disabled">Select Model</option>');

                        var selectedProductCategory = $scope.find('#ProductCategoryId').val();
                        if (selectedProductCategory !== '00000000-0000-0000-0000-000000000000') {
                            $J(ddlProductCategories).val(selectedProductCategory).change();
                        }
                        else {
                            $J(ddlProductCategories).val('').change();
                        }

                        var selectedProductSubCategory = $scope.find('#ProductSubCategoryId').val();
                        if (selectedProductSubCategory !== '00000000-0000-0000-0000-000000000000') {
                            $J(ddlProductSubCategories).val(selectedProductSubCategory).change();
                        }
                        else {
                            $J(selectedProductSubCategory).val('').change();
                        }

                        var selectedProduct = $scope.find('#ProductId').val();
                        if (selectedProduct !== '00000000-0000-0000-0000-000000000000') {
                            $J(ddlProduct).val(selectedProduct).change();
                            if (selectedProductCategory === '00000000-0000-0000-0000-000000000000') {
                                $J(ddlProductSubCategories).val(selectedProductCategory).change();
                            }
                        }
                    }
                }

                function applyEventBindings($scope) {
                    $scope.off("change", "#ddlProductCategories");
                    $scope.on("change", "#ddlProductCategories", function () {
                        var $this = $J(this);
                        var ddlProductSubCategories = $J('#ddlProductSubCategories');
                        var ddlProduct = $J('#ddlProduct');
                        $J(ddlProductSubCategories).empty().append('<option selected="selected" value="">Select Subcategory</option>');
                        $J(ddlProduct).empty().append('<option selected="selected" value="" disabled="disabled">Select Model</option>');
                        if ($this.val() !== '' && $this.val() != null) {
                            var categories = contentsSource.ProductCategories.filter(function (q) {
                                return q.SitecoreItemId === $this.val();
                            });

                            $scope.find('#ProductCategoryId').val($this.val());

                            var pcs = sortResults("SitecoreItemName", true, categories[0].SubCategories);
                            $.each(pcs, function () {
                                $J(ddlProductSubCategories).append($J("<option></option>").val(this['SitecoreItemId']).html(this['SitecoreItemName']));
                            });

                        }
                        else {
                            $J(ddlProductSubCategories).val();
                            $J(ddlProduct).val('');
                        }

                    });

                    $scope.off("change", "#ddlProductSubCategories");
                    $scope.on("change", "#ddlProductSubCategories", function () {
                        var $this = $J(this);
                        var ddlProduct = $J('#ddlProduct');
                        $J(ddlProduct).empty().append('<option selected="selected" value="" disabled="disabled">Select Model</option>');
                        $J(".divproduct").show();
                        if ($this.val() !== '' && $this.val() != null) {
                            var categories = contentsSource.ProductCategories.filter(function (q) {
                                return q.SitecoreItemId === $J("#ddlProductCategories").val();
                            });

                            $scope.find('#ProductSubCategoryId').val($this.val());

                            var subCategories = categories[0].SubCategories.filter(function (q) {
                                return q.SitecoreItemId === $this.val();
                            });

                            if (subCategories[0].SitecoreTemplateId !== $J("#ProductTemplateId").val()) {
                                var prds = sortResults("SitecoreItemName", true, subCategories[0].Products);
                                $.each(prds, function () {
                                    $J(ddlProduct).append($J("<option></option>").attr('data-hashelpcontent', this['HasHelpContent']).val(this['SitecoreItemName']).html(this['Heading']));
                                });
                            } else {
                                $J(".divproduct").hide();
                                $J(ddlProduct).append($J("<option></option>").attr('data-hashelpcontent', this['HasHelpContent']).val(subCategories[0].SitecoreItemId).html(subCategories[0].SitecoreItemName));
                                $J(ddlProduct).val($this.val()).change();

                            }
                        }
                    });

                    $scope.off("change", "#ddlProduct");
                    $scope.on("change", "#ddlProduct", function () {
                        var $this = $J(this);
                        if ($this.val() !== '' && $this.val() != null) {
                            var hiddenPrinterCategoryProductId = $scope.find('#PrinterProductCategoryId').val();
                            var categoryId = $("#ddlProductCategories option:selected").val();
                            if (categoryId.length === 0)
                                categoryId = "";

                            $scope.find('#ProductId').val($this.val());
                        }

                    });

                }

                function sortResults(prop, asc, items) {
                    items = items.sort(function (a, b) {
                        if (asc) {
                            return (a[prop] > b[prop]) ? 1 : ((a[prop] < b[prop]) ? -1 : 0);
                        } else {
                            return (b[prop] > a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0);
                        }
                    });

                    return items;
                }

                function configureTypeAhead($scope) {
                    if ($(".product-model-type-ahead").length > 0) {
                        $('body').delegate('.product-model-type-ahead', 'focus', function () {
                            $(".product-model-type-ahead").typeahead({
                                source: $.debounce(function (query, response) {
                                    searchProducts(query, response);
                                }, 300),
                                minLength: 2,
                                items: "8",
                                afterSelect: function (selectedItem) {
                                    console.log("selectedItem", selectedItem);
                                    var ddlProductCategories = $scope.find('#ddlProductCategories');
                                    var ddlProductSubCategories = $scope.find('#ddlProductSubCategories');
                                    var ddlProduct = $scope.find('#ddlProduct');
                                    $(ddlProductCategories).find(`option[value="${selectedItem.CategoryItemId}"]`).prop('selected', true).change();
                                    setTimeout(() => {
                                        $(ddlProductSubCategories).find(`option[value="${selectedItem.SubcategoryItemId}"]`).prop('selected', true).change();
                                        setTimeout(() => {
                                            $(ddlProduct).find(`option[value="${selectedItem.ModelItemName}"]`).prop('selected', true).change();
                                        }, 100)
                                    }, 100)
                                    $(".product-model-type-ahead").val("");
                                }
                            });
                        });
                    }
                }
                

            },

            initProductFeedFilter: function () {

                //Product Filter Type
                $J('.product-filter-type select').change(function () {
                    var selectedFilterType = '';
                    $(this).find('option:selected').each(function () {
                        selectedFilterType = $(this).val();
                        $J(this).removeAttr('selected');
                    });

                    var container = $J(this).closest('.cf06');
                    container.find(".product-filter-container li").each(function () {
                        if (!$J(this).hasClass("hide--me") && !$J(this).hasClass("all")) {
                            $J(this).addClass("hide--me");
                        }
                        if ($J(this).hasClass("all") && !$J(this).hasClass('active')) {
                            $J(this).addClass('active');
                        }
                        if ($J(this).attr('data-filter-type') === selectedFilterType) {
                            $J(this).removeClass("hide--me");
                        }
                        if ($J(this).hasClass("all")) {
                            $J(this).trigger('click');
                        }
                    });

                    container.find(".product-filter-container select option").each(function () {
                        if (!$J(this).hasClass("hide--me") && !$J(this).hasClass("all")) {
                            $J(this).addClass("hide--me");
                        }

                        $J(this).removeAttr('selected');

                        if ($J(this).hasClass('all')) {
                            $J(this).attr('selected');
                        }
                        if ($J(this).attr('data-filter-type') === selectedFilterType) {
                            $J(this).removeClass("hide--me");
                        }
                    });

                    container.find(".product-filter-container select").val('');

                    $J(this).val(selectedFilterType);

                });

                //List of product Filter by, on desktop
                $J(".product-filter-container li").on('click', function () {
                    var tileContainer = $J(this).closest('.cf06').siblings('.cf10').find('.product-listing-component');
                    var sourceId = $J(tileContainer).attr('data-source');


                    var postData = {
                        ProductParentId: sourceId,
                        PageIndex: 0,
                        PageSize: 15,
                        SelectedFilter: $J(this).attr('data-filter'),
                        IsPartnerRequest: $J(tileContainer).attr('data-isPartnerRequest')
                    };

                    $J(this).parent('ul').find('li').each(function () {
                        $J(this).removeClass("active");
                    });

                    $J(this).addClass("active");

                    $J(this).closest('.product-filter-container').find('option').each(function () {
                        $J(this).removeAttr('selected');

                        if ($J(this).val() === postData.SelectedFilter) {
                            $J(this).attr('selected', '');
                            $J(this).parent('select').val(postData.SelectedFilter);
                        }
                    });

                    defaultFunctions.getProductsFeed(postData, tileContainer, false, true);

                });

                //List of product Filter by, on mobile
                $J(".product-filter-container select").change(function () {

                    var selectedFilter = '';
                    $(this).find('option:selected').each(function () {
                        selectedFilter = $(this).val();
                        $J(this).removeAttr('selected');
                    });

                    $J(this).attr('selected', '');

                    if ($J(this).closest('.mobile').css('display') !== 'none') {
                        $J(this).closest('.product-filter-container').find('li').each(function () {
                            if ($J(this).attr('data-filter') === selectedFilter) {
                                $J(this).trigger('click');
                            }
                        });
                    }

                });
            },
            initProductFeedv3LoadMore: function () {
                $J('.product-load-more-feed-v3 a').on('click', function (e) {
                    e.preventDefault();
                    var container = $J(this).closest('.cf10').siblings('.cf06');

                    var selectedFilter = '';
                    $J(container).find('.product-filter-container li').each(function () {
                        if ($J(this).hasClass('active')) {
                            selectedFilter = $J(this).attr('data-filter');
                        }
                    });

                    var tileContainer = $J(this).parent().siblings('.product-listing-component-v3');
                    var sourceId = $J(tileContainer).attr('data-source');

                    var currentPageIndex = $J(this).attr("data-current-page");
                    var pageToRender = parseInt(currentPageIndex) + 1;

                    var postData = {
                        ProductParentId: sourceId,
                        PageIndex: pageToRender,
                        PageSize: 15,
                        SelectedFilter: selectedFilter,
                        IsPartnerRequest: $J(tileContainer).attr('data-isPartnerRequest')
                    };

                    $J(this).blur();
                    defaultFunctions.getProductsFeed(postData, tileContainer, true, false);
                });
            },
            initProductFeedLoadMore: function () {
                $J('.product-load-more-feed a').on('click', function (e) {
                    e.preventDefault();

                    var container = $J(this).closest('.cf10').siblings('.cf06');

                    var selectedFilter = '';
                    $J(container).find('.product-filter-container li').each(function () {
                        if ($J(this).hasClass('active')) {
                            selectedFilter = $J(this).attr('data-filter');
                        }
                    });

                    var tileContainer = $J(this).parent().siblings('.product-listing-component');
                    var sourceId = $J(tileContainer).attr('data-source');

                    var currentPageIndex = $J(this).attr("data-current-page");
                    var pageToRender = parseInt(currentPageIndex) + 1;

                    var postData = {
                        ProductParentId: sourceId,
                        PageIndex: pageToRender,
                        PageSize: 15,
                        SelectedFilter: selectedFilter,
                        IsPartnerRequest: $J(tileContainer).attr('data-isPartnerRequest')
                    };

                    $J(this).blur();
                    defaultFunctions.getProductsFeed(postData, tileContainer, true, false);
                });
            },

            getProductsFeed: function (postData, tileContainer, isLoadMore, updateCounter) {
                canonHelper.showSpinner();
                var data = canonHelper.addAntiForgeryToken(postData);
                var post = $J.post('/content-tile/product/getproductlist', data);
                post.done(function (data) {
                    var template;
                    // Try loading the external template files
                    $.when($.get("/mustachetemplates/products-listing-feed-v2.0.html", function (source) { template = source; }))
                        .then(function () {
                            var loadMoreEl = $J(tileContainer).parent().find(".product-load-more-feed a");
                            var loadMoreContainerEl = $J(loadMoreEl).parent();

                            if (data.ContentListingFeedSkinnyTiles && data.ContentListingFeedSkinnyTiles.length > 0) {
                                var result = Mustache.to_html(template, data);
                                var dist = {};
                                $.each(data.ContentListingFeedSkinnyTiles, function (index, item) {
                                    dist[item.EAN] = { "url": window.location.origin + item.Url };
                                })
                                var jsonObject = JSON.stringify(dist, null, 2);
                                var jsVariable = JSON.parse(jsonObject);

                                if (isLoadMore) {
                                    $J(tileContainer).append(result);
                                } else {
                                    $J(tileContainer).html(result);
                                }
                                canonHelper.tileMarginFix($J(tileContainer));
                            }

                            if (updateCounter) {
                                var counterText = $J(tileContainer).closest('.cf10').find('.filterProducts');
                                if (counterText.length > 0) {
                                    counterText.text((parseInt(data.TotalPagesFound) == 1 ? "is" : "are") + " " + data.TotalPagesFound + " " + (parseInt(data.TotalPagesFound) > 1 ? "products" : "product"));
                                }
                            }

                            if (data && data.IsNextPageAvailable) {
                                var loadMoreText = "<span>Load more " + data.TilesTypeForLoadMore + "</span><br>" + "(" + data.NextItemToDisplayed + ") " + data.TilesCounterForLoadMore + " left";
                                $J(loadMoreEl).html(loadMoreText);
                                $J(loadMoreEl).attr("data-current-page", data.CurrentPageIndex);
                                $J(loadMoreContainerEl).removeClass('hide--me');
                            } else {
                                if (!loadMoreContainerEl.hasClass('hide--me')) {
                                    loadMoreContainerEl.addClass('hide--me');
                                }
                            }

                            canonHelper.hideSpinner();

                            defaultFunctions.initHatchButton();

                        },
                            function () {
                                // templates not loaded
                                var templateError = 'Error: Could not load plugin templates. Check the paths and ensure they have been uploaded. Paths will be wrong if you do not run this from a web server.'; console.log(templateError);
                                canonHelper.hideSpinner();
                            });
                });

                post.fail(function () {
                    canonHelper.hideSpinner();
                });

                post.always(function () {
                });
            },
            getSitecoreQueryString: function (element) {
                var sitecoreQueryString = "";
                $(element).find('.filter-heading').each((index_heading, element_heading) => {
                    var heading = $(element_heading).attr('data-filter-id'); var activeFilters = [];
                    $(element_heading).find("input[type=checkbox]").each((index_checkbox, element_checkbox) => { if ($(element_checkbox).prop('checked')) { activeFilters.push($(element_checkbox).attr('id')) } })
                    if (activeFilters.length > 0) { sitecoreQueryString += `${heading}=${activeFilters.toString()}&`; }
                })
                return sitecoreQueryString.slice(0, -1);
            },
            initProductFeedTilesLoadMore: function () {
                $J('.show-more').on('click', function (e) {
                    e.preventDefault();

                    var element_cb61 = $('.cb61').first();
                    var filterString = window.location.href.split('?')[1];
                    var tileContainer = $J(this).parent().siblings('.tile-container');
                    var sourceId = $J(tileContainer).attr('data-source');
                    var currentPageIndex = $J(this).attr("data-current-page");
                    var pageToRender = parseInt(currentPageIndex) + 1;
                    var sortValue = $('.cb61b').find('#cb61-sort-select').val();
                    var postData = {
                        ProductParentId: sourceId,
                        PageIndex: pageToRender,
                        PageSize: 9,
                        SelectedFilterType: 'productfeedfilter',
                        SelectedFilter: defaultFunctions.getSitecoreQueryString(element_cb61),
                        IsPartnerRequest: $J(tileContainer).attr('data-isPartnerRequest'),
                        Sort: sortValue !== undefined ? sortValue : 'Featured'
                    };

                    $J(this).blur();
                    defaultFunctions.getProductsFeedTiles(postData, tileContainer, true, false, false, filterString);
                });
            },
            getProductsFeedTiles: function (postData, tileContainer, isLoadMore, updateCounter, isFromProductFilter, filterString) {

                if (!isFromProductFilter) { canonHelper.showSpinner(); }
                var data = canonHelper.addAntiForgeryToken(postData);
                var post = $J.post('/content-tile/productfeed/getproductfeedlist', data);
                var element_cb61 = $('.cb61').first();
                var element_cb61b = $('.cb61b').first();
                var loadMoreEl = $J(tileContainer).parent().find(".show-more");
                var loadMoreContainerEl = $J(loadMoreEl).parent();
                var noResultFound = false;
                loadMoreContainerEl.hide();
                post.done(function (data) {
                    var template;
                    // validate if the url matches with the filter string then make the api call 
                    if (filterString !== null && filterString !== undefined && filterString !== window.location.href.split('?')[1]) { return; }
                    // Try loading the external template files
                    $.when($.get("/mustachetemplates/products-listing-feed-v5.1.html", function (source) { template = source; }))
                        .then(function () {

                            if (data.ContentListingFeedTiles && data.ContentListingFeedTiles.length > 0) {
                                var result = Mustache.to_html(template, data);
                                var loadmoreCount = $J('#loadmoreCount');
                                if (isLoadMore) {
                                    $J(tileContainer).append(result);
                                    loadmoreCount.text(parseInt(data.TilesCount));
                                } else {
                                    $J(tileContainer).html(result);
                                }
                                canonHelper.tileMarginFix($J(tileContainer));
                                // added for Compare Bucket mustache template
                                const cb58ItemsChanged = new Event('cb58ItemsChanged')
                                window.dispatchEvent(cb58ItemsChanged);
                                defaultFunctions.initHatchButton();
                            }

                            else {
                                $J(tileContainer).html("<div class='no-results'>No results found</div>");
                                noResultFound = true;
                            }
                            if (updateCounter) {
                                var counterText = $J('#filterCounter');
                                var totalPageCountText = $J('#totalPageCount');

                                if (counterText.length > 0 && noResultFound === false) {
                                    counterText.text(parseInt(data.TotalPagesFound) + " " + "result(s)");
                                    loadmoreCount.text(parseInt(data.TilesCount));
                                    totalPageCountText.text(parseInt(data.TotalPagesFound));
                                    for (let heading in data.FilterCount) {
                                        var count = data.FilterCount[heading]
                                        var filter_item = $(element_cb61).find("div[data-sitecore-id='" + heading + "']")
                                        $(filter_item[0]).find('.count').html('(' + count + ')');
                                        if (count == 0) {
                                            $(filter_item).addClass('disabled')
                                            $(filter_item).find('input').attr('disabled', true)
                                        }
                                        else {
                                            $(filter_item).removeClass('disabled')
                                            $(filter_item).find('input').attr('disabled', false)
                                        }
                                    }
                                }
                                else {
                                    counterText.text("0" + " " + "result(s)");
                                    // loadmoreCount.text("0");
                                }
                            }
                            var loadMoreText = 'Show more';
                            if (data && data.IsNextPageAvailable) {

                                $J(loadMoreEl).html(loadMoreText);
                                $J(loadMoreEl).attr("data-current-page", data.CurrentPageIndex);
                                loadMoreContainerEl.show();
                                loadMoreEl.show();
                                canonHelper.hideSpinner();
                            }
                            else if (noResultFound) {
                                loadMoreContainerEl.hide();
                                canonHelper.hideSpinner();
                            }
                            else {
                                loadMoreContainerEl.show();
                                loadMoreEl.hide();
                                canonHelper.hideSpinner();
                                //show-more hide--me
                            }

                        },
                            function () {
                                // templates not loaded
                                var templateError = 'Error: Could not load plugin templates. Check the paths and ensure they have been uploaded. Paths will be wrong if you do not run this from a web server.'; console.log(templateError);
                                canonHelper.hideSpinner();
                            });

                    setTimeout(function () {
                        var template = $("#cf13-promo-tile").html();
                        if (!template) { return; }

                        //insert the promo tiles, if required.
                        if (data.PromoPrimary !== null && data.PromoPrimary.Position !== 0) {
                            var result = Mustache.to_html(template, data.PromoPrimary);
                            var location = $(".cf13 .tile-container> div:nth-child(" + (data.PromoPrimary.Position) + ")")
                            if (location.length == 0) {
                                $(".cf13 .tile-container").append(result);
                            }
                            else {
                                $(location).before(result);
                            }
                        }

                        if (data.PromoSecondary !== null && data.PromoSecondary.Position !== 0) {
                            var result = Mustache.to_html(template, data.PromoSecondary);
                            var location = $(".cf13 .tile-container> div:nth-child(" + (data.PromoSecondary.Position) + ")")
                            if (location.length == 0) {
                                $(".cf13 .tile-container").append(result);
                            }
                            else {
                                $(location).before(result);
                            }
                        }
                    },100)
                    

                    return false;
                });

                post.fail(function () {
                    canonHelper.hideSpinner();
                });
            },
            initHatchButton: function () {

                var responseData = $J.getJSON("/api/api/getpardotcookie");
                responseData.done(function (data) {
                    if (data != undefined && data.value != undefined && $.trim(data.value) !== "") {

                        var currentData = $J('.hatch-button').parent().attr("data-extra-request-parameters");
                        var newData = currentData.replace("'uid': 'undefined'", "'uid': '" + data.value + "'");

                        $J('.hatch-button').parent().attr("data-extra-request-parameters", newData);

                        HatchRequest.init();
                    }
                });

                HatchRequest.init();

                $(".hatch-button").on('click', function () {
                    setTimeout(function () {
                        if ($("[class^='hatch-widget'][role='presentation']").length > 1) {
                            $("[class^='hatch-widget'][role='presentation'][aria-hidden='true'] button[aria-label='close']").trigger('click');
                        }
                    }, 10);
                });
            },

            initHatchButtonProductList: function () {
                if ($('.tile--116b').length > 0) {
                    $J(window).load(function () {
                        setTimeout(function () {
                            defaultFunctions.initHatchButton();
                        }, 2500);
                    });
                }
            },

            initDxComponents: function () {
                if ($('.cb52') && $('.cb52').length > 0) {
                    var speedInMs = $('.cb52').attr("data-speed");
                    var enableAutoPlay = $('.cb52').attr("data-autoplay");

                    
                    $('[data-vbg]').youtube_background();

                    // todo - use this technique if buffer image is not sufficient in testing
                    // const VIDEO_CONTAINER_CLASS = '.cb01v'
                    // $(VIDEO_CONTAINER_CLASS).on('video-background-state-change', function (event) {
                    //     console.log('event.originalEvent.detail.currentState', event.originalEvent.detail.currentState); // the video instance object
                    // });

                    $('.cb52').slick({
                        infinite: false,
                        slidesToShow: 1,
                        slidesToScroll: 1,
                        autoplay: enableAutoPlay === "true",
                        autoplaySpeed: speedInMs,
                        dots: true,
                        pauseOnDotsHover: true,
                        adaptiveHeight: true,
                        mobileFirst: true,
                        arrows: true,
                        nextArrow: '<button type="button" class="slick-next"><a class="icomoon-LongArrowRight"></a></button>',
                        prevArrow: '<button type="button" class="slick-prev"><a class="icomoon-LongArrowLeft"></a></button>'
                    });
                }

                if ($('.gl3-meganav') && $('.gl3-meganav').length > 0) {
                    var acc1 = document.getElementsByClassName("accordion");
                    var i;
                    for (i = 0; i < acc1.length; i++) {
                        acc1[i].onclick = function () {
                            this.classList.toggle("active");
                            this.nextElementSibling.classList.toggle("show");
                        }
                    }

                    $(document).ready(function () {
                        $('#close-button').hide();
                        $('#mobile-menu').hide();
                    });

                    function getUrlVars() {
                        var vars = [],
                            hash;
                        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
                        for (var i = 0; i < hashes.length; i++) {
                            hash = hashes[i].split('=');
                            vars.push(hash[0]);
                            vars[hash[0]] = hash[1];
                        }
                        return vars;
                    }
                    function updateUrlVars(o) {
                        var wl = window.location;
                        var hashes = (wl.href.indexOf('?') > 0) ? wl.href.slice(wl.href.indexOf('?') + 1).split('&') : "";
                        var cloneHashes = [];
                        for (var i = 0, j = hashes.length; i < j; i++) {
                            if (hashes[i].indexOf("firsttime") >= 0 || hashes[i].indexOf("journey") >= 0) {
                                //do nothing
                            } else {
                                cloneHashes.push(hashes[i]);
                            }
                        }
                        //console.log(location.origin + location.pathname + "?" + cloneHashes.join("&"));
                        //console.log(hashes);
                        return location.origin + location.pathname + "?" + cloneHashes.join("&");
                    }
                    function showSearchModal(event) {
                        if ($('body.swipebox').length > 0) {
                            $('body').removeClass('swipebox');
                            return null;
                        }
                        $('body').removeClass('swipebox');
                        event.preventDefault();
                        var frame = '<div class="hero-modal2 search-context sb04" aria-hidden="true"><button class="close"></button><div class="container"> <div class="layout--1200"><div class="head--5 heading ">Type anything and hit enter</div><div class="inp"><button class="search-btn"></button><span class="highlight"></span><input class="search-term head--1" type="text" placeholder="What are you looking for?"><svg height="50" width="50" ng-show="showpreloader" class="circular"> <circle cx="25" cy="25" r="20" fill="none" stroke-width="2" stroke-miterlimit="10" class="path"></circle></svg></div><div class="total head--5 ">&nbsp;</div><div class="top-10 clearfix">&nbsp;</div><div class="tiled--4x results"> <ul> </ul> </div></div></div></div>';
                        $('body').prepend(frame);
                        TweenMax.fromTo($(".hero-modal2.sb04"), 0.5, {
                            css: {
                                opacity: 0
                            }
                        }, {
                            css: {
                                opacity: 1
                            }
                        });
                        var gs = globalSearch();
                        gs._init($(".sb04"), "suggest");
                        //document.body.style.overflow = "hidden";
                        $("body").addClass("overlay-open");
                        $(".sb04 .close").on("click", function () {
                            TweenMax.to($(".hero-modal2.sb04"), 0.5, {
                                css: {
                                    opacity: 0
                                },
                                onComplete: function () {
                                    $(".hero-modal2.sb04").remove();
                                }
                            });

                            $(this).unbind("click");
                            $("body").removeClass("overlay-open");
                            //document.body.style.overflow = "";
                        });
                    };
                    function showSearchPage(query) {
                        var gs = globalSearch();
                        gs._init($(".sb04a"), "simple", query);
                    };
                    var globalSearch = function () {
                        var $scope, $data = [],
                            $listItems, endTimer = 1850,
                            triggerLength = 2;
                        var keyTimer, searchTerm, queryType;
                        var region = (location.href.indexOf("co.nz") > 0) ? "nz" : "au";
                        var gsaHost = "//api.canon.com.au/gsa/SearchService.svc/";
                        var gsaCollection = (region == "nz") ? "collection=canon_nz" : "collection=canon";
                        var gsaLimit = "limit=10";
                        var gsaFrontend = "frontend=canon_json";
                        var gsaHostSimple = "simple?" + gsaCollection + "&" + gsaFrontend + "&page_size=50&" + gsaLimit + "&query=";
                        var gsaHostSuggest = "suggest?" + gsaCollection + "&" + gsaFrontend + "&" + gsaLimit + "&query=";
                        var suggest = "";
                        var shop = (region === "au") ? "//store.canon.com.au/?EAN=" : "//shop.canon.co.nz/?EAN=";


                        function init() {
                            $(".search-btn").on("click", function () {
                                console.log($('html').attr('class'));
                                $scope.find("input").blur();
                                //$(".sb04 input").disabled;
                                lookup2("suggest", searchTerm);
                                clearTimeout(keyTimer);
                                refresh();
                            });
                            if (searchTerm) {
                                $scope.find("input").val(searchTerm);
                                lookup2(queryType, searchTerm);
                            }
                            $scope.find("input").focus().on("keyup", function (e) {
                                // To make the search highlight line grow/shrink with user input
                                $scope.find(".highlight").text($(this).val());
                                $scope.find(".highlight").text($(this).val());

                                var code = e.which;

                                if (code == 13 && $(this).val().length > 2) {
                                    window.location.href = '/search?q=' + searchTerm;
                                    //lookup2("suggest", searchTerm);
                                    //clearTimeout(keyTimer);
                                    //refresh();
                                    return null;
                                }
                                if ($(this).val().length < triggerLength) {
                                    suggest = "";
                                    // refresh();
                                    return;
                                }
                                clearTimeout(keyTimer);
                                searchTerm = $(this).val();
                                keyTimer = setTimeout(function () {
                                    lookup2(queryType, searchTerm)
                                }, endTimer);
                            });
                        }

                        function refresh() {
                            $scope.find(".tiled--4x ul li").remove();
                            $scope.find(".total").html(" ");
                            //$scope.find(".top-10").html(" ");
                        }

                        function createTile() {
                            var arg = arguments;
                            var t;
                            if (typeof arg[0] != "object") return;
                            switch (arg[0].type) {
                                case "store":
                                case "explore":
                                    tx = createElement("div",
                                        createElement("h2", arg[0].hd, "heading") +
                                        createElement("a", arg[0].l1.link, arg[0].l1.text, "link1"), "txt-content");
                                    l1 = createElement("a", arg[0].l2.link, arg[0].l2.text, "link2 section")
                                    t = createElement("li", tx + l1, "tile--200");
                                    break;
                                case "article":
                                case "news":
                                    i = createElement("div",
                                        createElement("div",
                                            createElement("img", arg[0].im), "img-content"), "aratio--35-24");
                                    tx = createElement("div",
                                        createElement("h2", arg[0].hd, "heading") +
                                        createElement("p", arg[0].cp, "desc"), "txt-content");
                                    l1 = createElement("a", arg[0].l2.link, arg[0].l2.text, "link2 section");
                                    t = createElement("li", createElement("a", arg[0].l1, i + tx) + l1, "tile--112");
                                    break;
                                case "generic":
                                    i = createElement("div",
                                        createElement("div",
                                            createElement("img", arg[0].im), "img-content"), "aratio--35-24");
                                    tx = createElement("div",
                                        createElement("h2", arg[0].hd, "heading") +
                                        createElement("p", arg[0].cp, "desc"), "txt-content");
                                    t = createElement("li", createElement("a", arg[0].l1, i + tx), "tile--111");
                                    break;
                                case "event":
                                    i = createElement("div",
                                        createElement("div",
                                            createElement("img", arg[0].im), "img-content"), "aratio--35-24");
                                    tx = createElement("div",
                                        createElement("h2", arg[0].hd, "heading") +
                                        createElement("div", arg[0].l2, "date") +
                                        createElement("div", (arg[0].l3 != "") ? '<span class="icon-svg-location"></span>' + arg[0].l3 : '', "location") +
                                        createElement("div", '<span class="icon-svg-pricetag"></span>' + arg[0].l4, "cost") +
                                        createElement("div", (arg[0].l5 != "") ? '<span class="icon-svg-time"></span>' + arg[0].l5 : '', "duration"), "txt-content");
                                    l1 = createElement("a", arg[0].l6.link, arg[0].l6.text, "link2");
                                    t = createElement("li", createElement("a", arg[0].l1, i + tx) + l1, "tile--160");
                                    break;
                                case "product":
                                    i = createElement("div",
                                        createElement("div",
                                            createElement("img", arg[0].im), "img-content"), "aratio--35-24");
                                    tx = createElement("div", createElement("h2", arg[0].hd, "heading") +
                                        createElement("a", arg[0].l1.link, arg[0].l1.text + '<span class="icomoon-LongArrowRight">', "shop") +
                                        createElement("ul", createElement("li", createElement("a", arg[0].l2.link, arg[0].l2.text), arg[0].l2.cls) +
                                            createElement("li", createElement("a", arg[0].l3.link, arg[0].l3.text), arg[0].l3.cls) +
                                            createElement("li", createElement("a", arg[0].l4.link, arg[0].l4.text), arg[0].l4.cls) +
                                            createElement("li", createElement("a", arg[0].l5.link, arg[0].l5.text))) +
                                        createElement("a", arg[0].l6.link, "View product", "view"), "txt-content");
                                    t = createElement("li", i + tx, "tile--161", 'id="' + arg[0].id + '"');
                                    break;
                                default:

                            }
                            return t;
                        }

                        function createElement() {
                            var arg = arguments,
                                e;
                            switch (arg[0]) {
                                case "img":
                                    e = '<img src="' + (String(arg[1]).replace("staging", "www")).replace("cropregion", "cr") + '" alt="">';
                                    break;
                                case "h2":
                                    e = '<h2 class="' + (arg[2] || "") + '">' + arg[1] + '</h2>';
                                    break;
                                case "div":
                                    if (arg[1] == "") return "";
                                    e = '<div class="' + (arg[2] || "") + '">' + arg[1] + '</div>';
                                    break;
                                case "li":
                                    if (arg[1] == "") return "";
                                    e = '<li class="' + (arg[2] || "") + '" ' + (arg[3] || "") + '>' + arg[1] + ' </li>';
                                    break;
                                case "ul":
                                    e = '<ul class="' + (arg[2] || "") + '">' + arg[1] + '</ul>';
                                    break;
                                case "a":
                                    if (arg[1] == "") return "";
                                    if (arg[1].indexOf("/") < 0) return "";
                                    e = '<a href="' + arg[1] + '" class="' + (arg[3] || "") + '">' + arg[2] + '</a>';
                                    break;
                                case "p":
                                    e = '<p class="' + (arg[2] || "") + '">' + arg[1] + '</p>';
                                    break;
                                default:
                            }
                            return e;
                        }

                        function lookup2(t, q) {
                            //console.log(t, q);
                            $scope.find(".circular").css("display", "block");
                            $scope.find(".search-btn").css("visibility", "hidden");
                            $.getJSON(gsaHost + ((t == "suggest") ? gsaHostSuggest : gsaHostSimple) + ((t == "suggest") ? q.slice(0, -1) : q), {
                                format: "json"
                            }).done(function (data) {
                                if (t == "suggest") {
                                    //console.log('--> Suggest', data, data.suggestions, data.suggestions.length);
                                    if (data.suggestions && data.suggestions.length > 0) {
                                        /* does it contain it */
                                        if (data.suggestions[0].indexOf(q) >= 0) {
                                            suggest = data.suggestions[0];
                                            lookup2("simple", suggest);
                                            var ul = '';
                                            $.each(data.suggestions, function (i, item) {
                                                ul += "<li>" + item + "</li>";
                                            });
                                            if (ul.length > 0 && ul != undefined && ul != '') {
                                                $scope.find('.top-10').html("<span>Top " + data.suggestions.length + " suggested search terms: </span><ul>" + ul + "</ul>");
                                            }
                                        } else {
                                            if (data.suggestions.indexOf(q) > 0) {
                                                lookup2("simple", data.suggestions[data.suggestions.indexOf(q)]);
                                            } else {
                                                lookup2("simple", q);
                                            }
                                            //console.log("-->", data.suggestions.indexOf(q));

                                        }
                                        //if (suggest != data.suggestions[0]) {
                                        // suggest = data.suggestions[0];
                                        /* suggestQuery(suggest); */
                                        //suggest = data.suggestions[0];
                                        //if(data.suggestions.length > 3) {
                                        //suggest = data.suggestions[0] + "+" + data.suggestions[1];
                                        //}
                                        //lookup2("simple", suggest);
                                        //}
                                    } else {
                                        $scope.find(".total").html("No matched results for " + q);
                                        lookup2("simple", q);
                                    }
                                } else {
                                    $data = data.data;
                                    simpleQuery();
                                }
                            }).fail(function (jqxhr, textStatus, error) {
                                var err = textStatus + ", " + error;
                                //console.log("Request Failed: " + err);
                                suggest = "";
                                refresh();
                            });
                        }

                        function simpleQuery() {
                            var id = 0;
                            delay = 0.1;
                            //$scope.find(".total").html("Displaying " + $data.results_nav.results_end + " results");
                            // console.log($data);
                            refresh();

                            var circle = setTimeout(function () {
                                $scope.find(".circular").css("display", "none");
                                $scope.find(".search-btn").css("visibility", "visible");
                            }, 1500);
                            $.each($data.results, function (i, item) {
                                // console.log(item)
                                if (!item.title) return null; // ignore pages with no title
                                if (item.url.indexOf("store") > 0) return null; //ignore pages from store
                                var metatags = item.meta_tags;
                                var title = item.title.replaceAll('<b>', '').replaceAll('</b>', '').replaceAll('Canon Australia \\| ', '');
                                var image = findMeta("og:image", item.meta_tags, false)
                                if (image === null || String(image.length) < 20) {
                                    var altImage = findMeta("image", item.meta_tags, false)
                                    if (altImage) image = altImage
                                    // if(!altImage) {
                                    //     console.log('no image', item)
                                    // }
                                }
                                var path = item.url.split("/");
                                var local = path[0] + "/" + path[1] + "/" + path[2];
                                var pageTemplate = findMeta("page-template", item.meta_tags, false);
                                // console.log(pageTemplate)
                                image = String(image).replace("staging", "www");
                                image = String(image).replace("cropregion", "cr");
                                /*if (pageTemplate == "Product SubCategory Page" || pageTemplate == "Product Category Page" || pageTemplate == "Product Support Page" || pageTemplate == "Product Support Category Page" || pageTemplate == "Homepage" || pageTemplate == "Business Category Page") {
                                 return null;
                                 }*/
                                if (item.url.indexOf(".ashx") > 0) {
                                    return null;
                                }
                                /*if (pageTemplate == "Generic Page") {
                                 return null;
                                 }
                                 if (item.url == null) {
                                 return null;
                                 }*/

                                id++;
                                delay += 0.15;

                                if (pageTemplate == "Product Page") {
                                    //
                                    //findMeta("twitter:title", item.meta_tags, true);
                                    // console.log(image)
                                    // console.log(item);
                                    var t = findMeta("twitter:title", item.meta_tags, false);
                                    if (t == "New Templates") {
                                        t = findMeta("page-category", item.meta_tags, false) || title;
                                    }
                                    var sl = findMeta("store-link", item.meta_tags, false) || (findMeta("ean", item.meta_tags, false)) ? shop + findMeta("ean", item.meta_tags, false) : "";
                                    var st = (findMeta("store-link", item.meta_tags, false)) ? findMeta("store-text", item.meta_tags, false) : "Shop Now";
                                    if (findMeta("ean", item.meta_tags, false) == "") sl = "";
                                    item = {
                                        type: "product",
                                        hd: t,
                                        im: image || local + "/~/media/images/search/placeholder-products",
                                        id: id,
                                        l1: {
                                            link: sl,
                                            text: st
                                        },
                                        l2: {
                                            link: findMeta("downloads", item.meta_tags, false),
                                            text: "Downloads",
                                            cls: "download"
                                        },
                                        l3: {
                                            link: "/explore/learning",
                                            text: "Learning",
                                            cls: "learning"
                                        },
                                        l4: {
                                            link: "/explore/stories",
                                            text: "Stories",
                                            cls: "story"
                                        },
                                        l5: {
                                            link: findMeta("service-and-repair", item.meta_tags, false),
                                            text: "Service & repairs"
                                        },
                                        l6: {
                                            link: item.url,
                                            text: "View product"
                                        }
                                    };
                                } else if (pageTemplate == "News Page") {
                                    item = {
                                        type: "news",
                                        hd: findMeta2(['title', 'twitter:title', 'Business'], item.meta_tags, false),
                                        im: image || local + "/~/media/images/search/placeholder-products",
                                        l1: item.url,
                                        cp: findMeta2(['description', 'short-description', 'twitter:description', 'og:description', 'Service notice'], item.meta_tags, false),
                                        l2: {
                                            link: findMeta("breadcrumb-link", item.meta_tags, false),
                                            text: findMeta("breadcrumb", item.meta_tags, false)
                                        }
                                    };
                                } else if (pageTemplate == "Learning Page" || pageTemplate == "Story Page") {
                                    item = {
                                        type: "article",
                                        hd: findMeta("twitter:title", item.meta_tags, false),
                                        im: image,
                                        l1: item.url,
                                        cp: findMeta("description", item.meta_tags, false),
                                        l2: {
                                            link: findMeta("breadcrumb-link", item.meta_tags, false),
                                            text: findMeta("breadcrumb", item.meta_tags, false)
                                        }
                                    };
                                } else if (pageTemplate == "News Landing Page" || pageTemplate == "Explore Category Page" || pageTemplate == "Explore Homepage" || pageTemplate == "Explore By Page") {
                                    item = {
                                        type: "explore",
                                        hd: findMeta("description", item.meta_tags, false) || findMeta("twitter:title", item.meta_tags, false),
                                        l1: {
                                            link: item.url,
                                            text: "Read Story"
                                        },
                                        l2: {
                                            link: item.url,
                                            text: findMeta("breadcrumb", item.meta_tags, false) || "More"
                                        }
                                    };
                                } else if (pageTemplate == "Landing Page") {

                                    item = {
                                        type: "explore",
                                        hd: findMeta("description", item.meta_tags, false) || findMeta("twitter:title", item.meta_tags, false),
                                        l1: {
                                            link: item.url,
                                            text: "Read More"
                                        },
                                        l2: {
                                            link: item.url,
                                            text: findMeta("breadcrumb", item.meta_tags, false) || "Read More"
                                        }
                                    };
                                } else if (pageTemplate == "Standard Event Page") {
                                    item = {
                                        type: "event",
                                        hd: findMeta("Title", item.meta_tags, false),
                                        im: image,
                                        l1: item.url,
                                        l2: findMeta("Date", item.meta_tags, false),
                                        l3: findMeta("Location", item.meta_tags, false),
                                        l4: findMeta("Cost", item.meta_tags, false),
                                        l5: findMeta("Duration", item.meta_tags, false),
                                        l6: {
                                            link: item.url,
                                            text: "Event details"
                                        }
                                    };
                                } else if (pageTemplate == "Business Category Page") {
                                    var jic = item.url.split('/');
                                    jic = toTitleCase(jic[jic.length - 1].split('-').join(' ').split('?')[0]);
                                    item = {
                                        type: "generic",
                                        hd: findMeta2(['title', 'twitter:title', 'Business'], item.meta_tags, false),
                                        im: findMeta2(['image', 'og:image', local + "/~/media/images/search/placeholder-business"], item.meta_tags, false),
                                        l1: item.url,
                                        cp: findMeta2(['description', 'short-description', 'twitter:description', 'og:description', 'site-section', jic], item.meta_tags, false)
                                    };
                                } else if (pageTemplate == "Product Support Page" || pageTemplate == "Service and Repairs Category Page") {
                                    item = {
                                        type: "generic",
                                        hd: findMeta2(['title', 'twitter:title', 'Product support'], item.meta_tags, false),
                                        im: findMeta2(['image', 'og:image', local + "/~/media/images/search/placeholder-support"], item.meta_tags, false),
                                        l1: item.url,
                                        cp: findMeta2(['description', 'short-description', 'twitter:description', 'og:description', 'Download drivers, software, firmware and manuals for your Canon product'], item.meta_tags, false)
                                    };
                                } else if (pageTemplate == "Support Page" || pageTemplate == "Product Support Category Page" || pageTemplate == "SIMS Content Page") {
                                    item = {
                                        type: "generic",
                                        hd: findMeta2(['title', 'twitter:title', 'Product support'], item.meta_tags, false),
                                        im: findMeta2(['image', 'og:image', local + "/~/media/images/search/placeholder-support"], item.meta_tags, false),
                                        l1: item.url,
                                        cp: findMeta2(['description', 'short-description', 'twitter:description', 'og:description', 'Download drivers, software, firmware and manuals for your Canon product'], item.meta_tags, false)
                                    };
                                } else if (pageTemplate == "Campaign Page") {
                                    item = {
                                        type: "generic",
                                        hd: findMeta2(['title', 'twitter:title', 'Product support'], item.meta_tags, false),
                                        im: findMeta2(['image', 'og:image', local + "/~/media/images/search/placeholder-product"], item.meta_tags, false),
                                        l1: item.url,
                                        cp: findMeta2(['description', 'short-description', 'twitter:description', 'og:description', 'Campaigns'], item.meta_tags, false)
                                    };
                                } else if (pageTemplate == "Generic Page") {
                                    item = {
                                        type: "generic",
                                        hd: findMeta2(['title', 'twitter:title', 'Canon Information'], item.meta_tags, false),
                                        im: findMeta2(['image', 'og:image', local + "/~/media/images/search/placeholder-explore"], item.meta_tags, false),
                                        l1: item.url,
                                        cp: findMeta2(['description', 'short-description', 'twitter:description', 'og:description', 'Campaigns'], item.meta_tags, false)
                                    };
                                } else if (pageTemplate == "Business Homepage") {
                                    item = {
                                        type: "generic",
                                        hd: findMeta2(['title', 'twitter:title', 'Business'], item.meta_tags, false),
                                        im: findMeta2(['image', 'og:image', local + "/~/media/images/search/placeholder-business"], item.meta_tags, false),
                                        l1: item.url,
                                        cp: findMeta2(['description', 'short-description', 'twitter:description', 'og:description', 'Canon Business Information'], item.meta_tags, false)
                                    };
                                } else if (pageTemplate == "Product Category Page" || pageTemplate == "Product SubCategory Page") {
                                    item = {
                                        type: "generic",
                                        hd: findMeta2(['title', 'twitter:title', 'Product Category'], item.meta_tags, false),
                                        im: findMeta2(['image', 'og:image', local + "/~/media/images/search/placeholder-products"], item.meta_tags, false),
                                        l1: item.url,
                                        cp: findMeta2(['description', 'short-description', 'twitter:description', 'og:description', 'Canon Product Information'], item.meta_tags, false)
                                    };
                                } else if (pageTemplate == "Homepage") {
                                    item = {
                                        type: "generic",
                                        hd: findMeta2(['title', 'twitter:title', 'Canon Homepage'], item.meta_tags, false),
                                        im: findMeta2(['image', 'og:image', local + "/~/media/images/search/placeholder-products"], item.meta_tags, false),
                                        l1: item.url,
                                        cp: findMeta2(['description', 'short-description', 'twitter:description', 'og:description', "Explore Canon Australia's range of products and services and check out our inspiring stories, events and tutorials. No one sees it like you"], item.meta_tags, false)
                                    };
                                } else if (pageTemplate == "" && item.url.indexOf('/about')) {
                                    var jic = item.url.split('/');
                                    jic = toTitleCase(jic[jic.length - 1].split('-').join(' ').split('?')[0]);
                                    item = {
                                        type: "generic",
                                        hd: findMeta2(['title', 'twitter:title', 'About Canon'], item.meta_tags, false),
                                        im: findMeta2(['image', 'og:image', local + "/~/media/images/search/placeholder-explore"], item.meta_tags, false),
                                        l1: item.url,
                                        cp: findMeta2(['description', 'short-description', 'twitter:description', 'og:description', jic], item.meta_tags, false)
                                    };
                                } else if (pageTemplate == "Major Event Page") {
                                    item = {
                                        type: "event",
                                        hd: findMeta("Title", item.meta_tags, false),
                                        im: image,
                                        l1: item.url,
                                        l2: findMeta("Date", item.meta_tags, false),
                                        l3: '',
                                        l4: findMeta("Cost", item.meta_tags, false),
                                        l5: '',
                                        l6: {
                                            link: item.url,
                                            text: "Event details"
                                        }
                                    };
                                } else {
                                    item = {
                                        type: "generic",
                                        hd: findMeta2(['title', 'twitter:title', 'Canon Information'], item.meta_tags, false),
                                        im: findMeta2(['image', 'og:image', local + "/~/media/images/search/placeholder-explore"], item.meta_tags, false),
                                        l1: item.url,
                                        cp: findMeta2(['description', 'short-description', 'twitter:description', 'og:description', 'Campaigns'], item.meta_tags, false)
                                    };
                                }

                                $scope.find(".results > ul").append(createTile(item));
                                if (id < 9) {
                                    TweenMax.fromTo($scope.find(".results > ul li#" + id), 0.45, {
                                        css: {
                                            opacity: 0,
                                            marginTop: "80"
                                        }
                                    }, {
                                        css: {
                                            opacity: 1,
                                            marginTop: "0"
                                        },
                                        delay: delay
                                    });
                                }

                            });
                            $scope.find(".total").html('<span class="soft">Top </span> ' + id + ' results <span class="soft">for</span> ' + searchTerm);
                            //suggest
                            tileMarginFix();
                        }

                        function toTitleCase(str) {
                            return str.replace(/\w\S*/g, function (txt) {
                                return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
                            });
                        }

                        function findMeta(s, o, d) {
                            var rtn = null;
                            $.each(o, function (i, item) {
                                if (d) console.log(item.name, item.value, s, item.name == s);
                                if (item.name == s) {
                                    rtn = item.value;
                                    return false;
                                }
                            });
                            return rtn;
                        }

                        function findMeta2(s, o, d) {
                            var rtn = s[s.length - 1];
                            $.each(o, function (i, item) {
                                if (d) console.log(item.name, item.value, s.indexOf(item.name));
                                if (s.indexOf(item.name) >= 0 && item.value.length > 0) {
                                    rtn = item.value;
                                    return false;
                                }
                            });
                            return rtn;
                        }

                        function seeYa() {
                            var delay = 0;
                            $scope.find(".results > ul li").reverse().each(function () {

                            });
                        }

                        return {
                            _init: function (s, t, q) {
                                $scope = s;
                                queryType = t;
                                searchTerm = q;
                                init();
                                refresh();
                            },
                            _refresh: function () {
                                refresh();
                            },
                            _destroy: function () {
                                seeYa();
                            }
                        }
                    };

                    //$(".search-button").on("click", showSearchModal);
                }

                if ($('.cg02')) {
                    $('.grid-carousel').slick({
                        infinite: false,
                        slidesToShow: 3,
                        slidesToScroll: 1,
                        dots: true,
                        adaptiveHeight: true,
                        mobileFirst: true,
                        arrows: false,
                        responsive: [{
                            breakpoint: 843,
                            settings: {
                                slidesToShow: 3
                            }
                        }, {
                            breakpoint: 680,
                            settings: {
                                slidesToShow: 2
                            }
                        }, {
                            breakpoint: 400,
                            settings: {
                                slidesToShow: 2
                            }
                        }, {
                            breakpoint: 200,
                            settings: {
                                slidesToShow: 1
                            }
                        }]
                    });
                }
            },

            initNewProductFeedLoadMore: function () {
                $J('.prod__selector .product-load-more-feed a').on('click', function (e) {
                    var tileContainer = $J('.prod__selector').find('.product-listing-container');
                    var pagesize = $J('#pageSize').val();
                    var currentPageIndex = $J(this).attr("data-current-page");
                    var pageToRender = parseInt(currentPageIndex) + 1;

                    var filterUsage = $J('.prod__selector').find('button.selected');

                    var filterType = $J('input[name=productType]:checked');


                    var postData = {
                        PageIndex: pageToRender,
                        PageSize: pagesize,
                        DatasourceId: $J('.prod__selector').find('.filter-button-group').attr('id'),
                        SelectedTypes: [],
                        SelectedTypeCodes: []
                    };

                    if (filterUsage) {
                        postData.SelectedUsage = filterUsage.attr('id');
                        postData.SelectedUsageCode = filterUsage.data('filter_useage_code');
                    }

                    if (filterType) {
                        if (filterType.attr('id') != 'all') {
                            postData.SelectedTypes.push(filterType.attr('id'));
                            postData.SelectedTypeCodes.push(filterType.data('filter_type_code'));
                        }
                        else {
                            postData.SelectedTypes = [];
                            postData.SelectedTypeCodes = [];
                        }
                    }
                    defaultFunctions.getProductListingsFeed(postData, tileContainer, true, true);
                });
            },
            getProductListingsFeed: function (postData, tileContainer, isLoadMore, updateCounter) {

                canonHelper.showSpinner();
                var data = canonHelper.addAntiForgeryToken(postData);
                var post = $J.post('/content-tile/product/getproductlistings', data);
                post.done(function (data) {
                    var template;
                    // Try loading the external template files
                    $.when($.get("/mustachetemplates/products-listing-feed-new.html", function (source) { template = source; }))
                        .then(function () {
                            var loadMoreEl = $J('.prod__selector').find(".product-load-more-feed a");
                            var loadMoreContainerEl = $J(loadMoreEl).parent();

                            if (data.ContentListingFeedSkinnyTiles && data.ContentListingFeedSkinnyTiles.length > 0) {
                                var result = Mustache.to_html(template, data);
                                var dist = {};
                                $.each(data.ContentListingFeedSkinnyTiles, function (index, item) {
                                    dist[item.EAN] = { "url": window.location.origin + item.Url };
                                })
                                var jsonObject = JSON.stringify(dist, null, 2);
                                var jsVariable = JSON.parse(jsonObject);

                                if (isLoadMore) {
                                    $J(tileContainer).append(result);
                                } else {
                                    var typeallcheck = postData.SelectedTypes == undefined || postData.SelectedTypes === [] ? 'checked=checked' : '';
                                    var typeHtml = '';
                                    typeHtml += '<div class="filter-option">';
                                    typeHtml += '<input id="all" class="product-type" ' + typeallcheck + ' name="productType" type="checkbox">';
                                    typeHtml += '<label for="1">All</label>';
                                    typeHtml += '</div>';


                                    var $mobileProducttype = $J("#filter-option-mobile-producttype");
                                    $mobileProducttype.empty();
                                    var typeallSelected = postData.SelectedTypes == undefined || postData.SelectedTypes === [];

                                    $mobileProducttype.append($("<option></option>").attr("mobile_id", "all").attr("value", "all").text("All").prop('selected', typeallSelected));

                                    $.each(data.ProductTypes, function (index, productType) {
                                        var selected = postData.SelectedTypes.includes(productType.SitecoreItemId) ? 'checked=checked' : '';
                                        typeHtml += '<div class="filter-option">';
                                        typeHtml += '<input id="' + productType.SitecoreItemId + '" data-filter_type_code="' + productType.FilterKey + '" class="product-type" ' + selected + ' name="productType" type="checkbox">';
                                        typeHtml += '<label for="1">' + productType.FilterKey + '</label>';
                                        typeHtml += '</div>';

                                        var selectedMobile = postData.SelectedTypes.includes(productType.SitecoreItemId);
                                        $mobileProducttype.append($("<option></option>").attr("mobile_id", productType.SitecoreItemId).attr("value", productType.FilterKey).text(productType.FilterKey).prop('selected', selectedMobile));

                                    });

                                    $J("#filter-option-producttype").html(typeHtml);
                                    $J(tileContainer).html(result);
                                }
                                canonHelper.tileMarginFix($J(tileContainer));
                            }
                            else {
                                if (!isLoadMore) {
                                    $J(tileContainer).html('');
                                }
                            }

                            if (data && data.IsNextPageAvailable) {
                                var loadMoreText = "<span>Load more " + data.TilesTypeForLoadMore + "</span><br>" + "(" + data.NextItemToDisplayed + ") " + data.TilesCounterForLoadMore + " left";
                                $J(loadMoreEl).html(loadMoreText);
                                $J(loadMoreEl).attr("data-current-page", data.CurrentPageIndex);
                                $J(loadMoreContainerEl).removeClass('hide--me');
                            } else {
                                if (!loadMoreContainerEl.hasClass('hide--me')) {
                                    loadMoreContainerEl.addClass('hide--me');
                                }
                            }

                            defaultFunctions.initHatchButton();
                            canonHelper.hideSpinner();

                        },
                            function () {
                                // templates not loaded
                                var templateError = 'Error: Could not load plugin templates. Check the paths and ensure they have been uploaded. Paths will be wrong if you do not run this from a web server.'; console.log(templateError);
                                canonHelper.hideSpinner();
                            });
                });

                post.fail(function () {
                    canonHelper.hideSpinner();
                });

                post.always(function () {
                });
            },

            initAskToLoginBeforeBookEvent: function () {
                $J('.ask-to-login').on('click', function () {
                    var body = $J(this).closest('body');
                    var modal = body.find("div[data-remodal-id*='loginpopup']");
                    if (modal && modal.length > 0) {
                        var continueButton = $J(modal).find('.continue-booking');
                        if (continueButton && continueButton.length > 0) {
                            $J(continueButton).attr('href', $J(this).attr('data-booking-href'));
                        }
                    }
                });
            },

            initDisabledAnchor: function () {
                $J('a[disabled]').on('click', function (e) {
                    e.preventDefault();
                    e.stopPropagation();
                });
            },

            inputtextBoxNumberValidation: function () {
                $("input[type='number']").on('keyup keypress blur change', function (e) {
                    if ($(this).attr('maxlength') != undefined && $(this).attr('maxlength').length > 0) {
                        if (e.which !== 8 && e.which !== 0 && (e.which < 48 || e.which > 57)) {
                            return false;
                        } else {
                            if ($(this).val().length >= parseInt($(this).attr('maxlength')) && (e.which !== 8 && e.which !== 0)) {
                                return false;
                            }
                        }
                    }
                });
            },

            initProductTypeAhead: function () {
                if ($(".product-model-search-box") && $(".product-model-search-box").length > 0) {
                    function typeaheadSource(query, response) {
                        // This is going to make an HTTP post request to the controller3
                        canonHelper.showSpinner();
                        var post = $.post("/content/search/typeaheadforproduct", { query: query }, function (data) {
                            canonHelper.hideSpinner();
                            response(data);
                        }).fail(function () {
                            canonHelper.hideSpinner();
                        });

                        return post;
                    }

                    $('body').delegate('.product-model-search-box', 'focus', function () {
                        $(".product-model-search-box").typeahead({
                            source: $.debounce(function (query, process) {
                                typeaheadSource(query, process);
                            },300),
                            minLength: 3,
                            items: "8"
                        });
                    });
                }
            },

            HeaderStoreLinks: function () {
                $(".header-links li").on("click", function () {
                    var linkAttr = $(this).attr("data-attr-href");
                    var targetAttr = $(this).attr("data-attr-target");
                    if (linkAttr != undefined && linkAttr.length > 0) {
                        if (targetAttr === "_self") {
                            window.location.href = linkAttr;

                        } else {
                            window.open(linkAttr);
                        }
                    }
                });

                $('header.edge a.user-guide:not([href="#"])').off('click');
                $('header.edge a.search').parent('li').off('click');
            },

            loginMessageDisplay: function () {
                if ($J(".nav.toolbar li.new-user") && $J(".nav.toolbar li.new-user").length > 0) {
                    document.body.addEventListener('click', RemoveSinginMessage, true);
                }

                function RemoveSinginMessage() {
                    if ($J(".nav.toolbar li.new-user") && $J(".nav.toolbar li.new-user").length > 0) {

                        $(".nav.toolbar li.new-user").remove();
                        $(".nav.toolbar ul.sub-menu").removeClass("active");

                    }
                    document.body.removeEventListener('click', RemoveSinginMessage, true);
                }
                if ($J(".nav.toolbar li.new-user") && $J(".nav.toolbar li.new-user").length > 0) {
                    if (canonHelper.getCookie("Canon.SigninMessageDisplay") === "") {
                        canonHelper.setCookie("Canon.SigninMessageDisplay", 1, 1);
                    }
                }
            },

            initSdsFilter: function () {
                if ($('.ff01').length > 0) {
                    $('.ff01 input[type=radio][name="search-by"]').change(function () {
                        var searchElement = $(this).closest('.sds-search-container').find('#productname');
                        $(searchElement).val('');
                        $J(searchElement).attr('data-keyword', '');
                        $(searchElement).trigger(jQuery.Event('keypress', { keycode: 13 }));
                    });

                    $('.ff01 #productname').keypress(function (e) {
                        if (e.which === 13) {
                            var keyword = $J(this).val();
                            var currentKeyword = $J(this).attr('data-keyword');
                            if (currentKeyword == undefined || currentKeyword !== keyword) {
                                searchByKeyword(keyword, $J(this));
                                $J(this).attr('data-keyword', keyword);
                            }
                        }
                    });

                    function searchByKeyword(keyword, el) {

                        var container = $J(el).closest('.ff01');
                        var tileContainer = $(container).find(".results-list");
                        var searchByRadio = $(container).find('.sds-search-container input[type=radio][name="search-by"]:checked');
                        var searchByValue = searchByRadio && searchByRadio.length > 0 ? searchByRadio.val() : '';

                        var postData = {
                            Keyword: keyword,
                            SearchBy: searchByValue
                        };

                        defaultFunctions.getSdsFeed(postData, tileContainer, false);
                    }
                }
            },

            initSdsLoadMore: function () {
                $J('.sds-load-more-feed a').on('click', function (e) {
                    e.preventDefault();

                    var container = $J(this).closest('.ff01');
                    var searchInput = $J(container).find('#productname');
                    var keyword = searchInput && searchInput.length > 0 && searchInput.attr('data-keyword') ? searchInput.attr('data-keyword') : '';

                    var tileContainer = $(container).find(".results-list");
                    var currentPageIndex = $J(this).attr("data-current-page");
                    var pageToRender = parseInt(currentPageIndex) + 1;

                    var searchByRadio = $(container).find('.sds-search-container input[type=radio][name="search-by"]:checked');
                    var searchByValue = searchByRadio && searchByRadio.length > 0 ? searchByRadio.val() : '';

                    var postData = {
                        Keyword: keyword,
                        SearchBy: searchByValue,
                        PageIndex: pageToRender
                    };

                    $J(this).blur();

                    defaultFunctions.getSdsFeed(postData, tileContainer, true);
                });
            },

            edgeSearchLoadMore: function () {
                $J('.ff01.edge .edge-search-load-more-feed a').on('click', function (e) {
                    e.preventDefault();

                    var container = $J(this).closest('.ff01.edge');
                    var searchInput = $J(container).find('#searchbox');
                    var sortByElement = $J(container).find('#edge-search-order-by');
                    var filterByElement = $J(container).find('#edge-search-filter-by');

                    var tileContainer = $(container).find(".results-list");
                    var currentPageIndex = $J(this).attr("data-current-page");
                    var pageToRender = parseInt(currentPageIndex) + 1;
                    var postData = {
                        Query: $(searchInput).val(),
                        PageIndex: pageToRender,
                        SortBy: $(sortByElement).val(),
                        FilterBy: $(filterByElement).val()
                    };

                    //$J(this).blur();

                    defaultFunctions.getEdgeSearchFeed(postData, tileContainer, true);
                });
            },

            getEdgeSearchFeed: function (postData, tileContainer, isLoadMore) {
                canonHelper.showSpinner();

                var data = canonHelper.addAntiForgeryToken(postData);
                var post = $.post('/content-tile/edge/edgesearchloadmore', data);

                post.done(function (data) {
                    var template = $('.edge-search-file-template').html();
                    var loadMoreEl = $(".edge-search-load-more-feed a");
                    var resultContainer = $(".result-container");

                    var loadMoreContainerEl = $(loadMoreEl).parent();

                    if (data != undefined && data.Results != undefined) {
                        resultContainer.removeClass('hide--me');
                        var result = Mustache.to_html(template, data);
                        if (isLoadMore) {
                            $(tileContainer).append(result);
                        } else {
                            $(tileContainer).html(result);
                            var counterText = $(tileContainer).closest('.ff01').find(".result-total p");
                            counterText.text('You have ' + data.TotalItemsFound + ' results in total');
                        }
                        canonHelper.tileMarginFix($(tileContainer));
                        defaultFunctions.edgeSearchDebugMode();
                    }
                    else {
                        if (!resultContainer.hasClass('hide--me')) {
                            resultContainer.addClass('hide--me');
                        }
                    }

                    if (data && data.IsNextPageAvailable) {
                        var loadMoreText = "Load more<br><span>" + "(" + data.NextItemToDisplayed + " result left)</span>";
                        $(loadMoreEl).html(loadMoreText);
                        $(loadMoreEl).attr("data-current-page", data.CurrentPageIndex);
                        $(loadMoreContainerEl).removeClass('hide--me');
                    } else {
                        if (!loadMoreContainerEl.hasClass('hide--me')) {
                            loadMoreContainerEl.addClass('hide--me');
                        }
                    }

                    canonHelper.hideSpinner();
                });

                post.fail(function () {
                    canonHelper.hideSpinner();
                });
            },
            getSdsFeed: function (postData, tileContainer, isLoadMore) {
                canonHelper.showSpinner();

                var data = canonHelper.addAntiForgeryToken(postData);
                var post = $.post('/content-tile/safetydatasheet/getsafetydatasheetsearch', data);

                post.done(function (data) {

                    var template = $(tileContainer).closest('.ff01').find('.sds-file-template').html();
                    var loadMoreEl = $(tileContainer).closest('.ff01').find(".sds-load-more-feed a");
                    var resultContainer = $(tileContainer).closest('.ff01').find(".result-container");

                    var loadMoreContainerEl = $(loadMoreEl).parent();

                    if (data.SafetyDataSheetSkinnyItems) {
                        resultContainer.removeClass('hide--me');
                        var result = Mustache.to_html(template, data);
                        if (isLoadMore) {
                            $(tileContainer).append(result);
                        } else {
                            $(tileContainer).html(result);
                            var counterText = $(tileContainer).closest('.ff01').find(".result-total p");
                            counterText.text('You have ' + data.TotalItemsFound + ' results in total');
                        }
                        canonHelper.tileMarginFix($(tileContainer));
                    }
                    else {
                        if (!resultContainer.hasClass('hide--me')) {
                            resultContainer.addClass('hide--me');
                        }
                    }

                    if (data && data.IsNextPageAvailable) {
                        var loadMoreText = "Load more<br><span>" + "(" + data.NextItemToDisplayed + " result left)</span>";
                        $(loadMoreEl).html(loadMoreText);
                        $(loadMoreEl).attr("data-current-page", data.CurrentPageIndex);
                        $(loadMoreContainerEl).removeClass('hide--me');
                    } else {
                        if (!loadMoreContainerEl.hasClass('hide--me')) {
                            loadMoreContainerEl.addClass('hide--me');
                        }
                    }

                    canonHelper.hideSpinner();
                });

                post.fail(function () {
                    canonHelper.hideSpinner();
                });
            },

            glossaryLinkListLoadMore: function () {
                if ($J(".glossarylinklist") && $J(".glossarylinklist").length > 0) {

                    if ($J(".load-more-glossary-link-list").data("is-last-page") === "True") {
                        $J(".load-more-glossary-link-list").hide();
                    } else {
                        $J(".load-more-glossary-link-list").show();
                    }

                    $J(".load-more-glossary-link-list").off("click");
                    $J(".load-more-glossary-link-list").on("click", function () {
                        var $this = $J(this);
                        $this.blur();
                        defaultFunctions.glossaryLinkListLoadMoreEventHanlder($this);
                    });
                }
            },

            glossaryLinkListLoadMoreEventHanlder: function ($this) {
                var componentEl = $this.closest(".glossarylinklist");
                var datasourceItemId = componentEl.data("glossary-container");
                var currentItemId = componentEl.data("current-id");
                var template = $J(componentEl).find(".glossary-link-list-container-template").html();
                var feed = $J(componentEl).find("ul.glossarylinklistcontainer");
                var currentPageIndex = $this.data("current-index");
                var totalLinkItemsDisplayedOnPage = $this.data("total-link-items-displayed-on-page");
                var isLastPage = $this.data("is-last-page");

                if (isLastPage.toString().toLowerCase() === "false" || !isLastPage) {
                    currentPageIndex++;
                }

                canonHelper.showSpinner();

                var postData = {
                    CurrentPageIndex: currentPageIndex,
                    TotalLinkItemsDisplayedOnPage: totalLinkItemsDisplayedOnPage,
                    GlossaryContainerItemId: datasourceItemId,
                    CurrentItemId: currentItemId
                };

                var request = canonHelper.addAntiForgeryToken(postData);
                var post = $J.post("/content-tile/glossary/postglossarylinklist", request);

                post.done(function (data) {
                    if (data != "") {
                        if (data.LinkListItems != undefined) {
                            var result = Mustache.to_html(template, { LinkListItems: data.LinkListItems });

                            feed.append(result);

                            if (data.IsLastPage) {
                                $this.hide();
                            } else {
                                $this.data('current-index', data.CurrentPageIndex);
                                $this.data('total-link-items-displayed-on-page', data.TotalLinkItemsDisplayedOnPage);
                                $this.data('is-last-page', data.IsLastPage);
                                $this.show();
                            }

                            var loadmoreCounterText = "(" + data.TotalLinkItemsLeftCount + " items left)";
                            $J(".links-left").html(loadmoreCounterText);
                        }
                    }
                    canonHelper.hideSpinner();
                });

                post.fail(function () {
                    canonHelper.hideSpinner();
                });
            },

            initFormSubmission: function () {
                $J(function () {
                    if (canonHelper.getQueryString("refnumber") != '') {
                        $J(".reference-number span").text(canonHelper.getQueryString("refnumber"))
                    }
                    else {
                        $J(".form-reference").hide();
                    }
                });
            },

            downloadResourceFormOnSubmit: function (currentForm) {
                if ($J(currentForm).closest(".cp19") != undefined && $J(currentForm).closest(".cp19").length > 0) {
                    canonHelper.setCookie("CANON_RESOURCE_FORM_SUBMITTED", "1", 1);
                    $J(currentForm).closest(".eloqua-container").addClass("hide--me");
                    canonHelper.showSpinner();
                    var responseData = $J.getJSON("/content-tile/fastbusiness/downloadresourcemediaitem?mediaitemid=" + $.trim($J(currentForm).closest(".cp19").data("media-id")));
                    responseData.done(function (data) {
                        if (data != undefined && data.ResourceMediaItemUrl != undefined && $.trim(data.ResourceMediaItemUrl) != "") {
                            $J(currentForm).closest(".cp19").find(".download-resource").attr("href", data.ResourceMediaItemUrl);
                            $J(currentForm).closest(".cp19").find(".download-resource").removeClass("hide--me");
                            var $a = $('<a />', {
                                'href': data.ResourceMediaItemUrl,
                                'text': "click",
                                'target': "_blank"
                            }).hide().appendTo("body")[0].click();
                        }
                        canonHelper.hideSpinner();
                    });

                    responseData.fail(function () {
                        $J(currentForm).closest(".cp19").find(".download-resource").hide();
                        canonHelper.hideSpinner();
                    });
                    if ($J(currentForm).closest(".cp19") && $J(currentForm).closest(".cp19").offset() != undefined && $J(currentForm).closest(".cp19").offset().top != undefined) {
                        $('html, body').animate({
                            scrollTop: $J(currentForm).closest(".cp19").offset().top - $J(currentForm).closest(".eloqua-container").height() - 70
                        }, 1000);
                    }
                }
            },

            initEloquaForm: function () {
                $(".eloqua-message").hide();
                function eloqueForms() {
                    var $scope = $(".fm01.eloqua-container");
                    function init() {
                        $scope.find("input").on("blur focus keypress keyup", function (e) {
                            var currentForm = $J(this).closest('form');
                            var button = currentForm.find(".eloqua-submit");
                            /*if (currentForm[0].checkValidity()) {
                            button[0].disabled = false;
                        }
                        else {
                            button[0].disabled = true;
                        }*/
                            button[0].disabled = false;
                            if (e.type === "blur") {
                                var isValid = true;
                                if ($(this).attr("required") === "required" && $(this).val().length < 1 && $(this).next().is(".form-feedback")) {
                                    isValid = false;
                                }
                                if ($(this).attr("isemail")) {
                                    var re = new RegExp($(this).attr("pattern"));
                                    if (!re.test($(this).val())) {

                                    }
                                }
                                if (isValid) {
                                    var fieldValLength = $(this).val().length;
                                    if ($(this).attr("maxlength") && fieldValLength > $(this).attr("maxlength")) {
                                        $(this).addClass("error");
                                        $(this).next().addClass("error").find("span").text($(this).attr("lengthmessage"));
                                    }
                                    if ($(this).attr("minlength") && fieldValLength < $(this).attr("minlength")) {
                                        $(this).addClass("error");
                                        $(this).next().addClass("error").find("span").text($(this).attr("lengthmessage"));
                                    }
                                }
                            }
                        });

                        $scope.find("select").on("blur focus keypress keyup", function (e) {
                            if (e.type === "focus") {
                                $(this).removeClass("error");
                                if ($(this).parent().parent().find(".form-feedback")) {
                                    $(this).parent().parent().find(".form-feedback").removeClass("error");
                                }
                            }
                            if (e.type === "blur") {
                                if ($(this).attr("required") === "required" && $(this).prop("selectedIndex") < 1 && $(this).parent().parent().find(".form-feedback")) {
                                    $(this).addClass("error");
                                    $(this).parent().parent().find(".form-feedback").addClass("error").find("span").text($(this).attr("emptymessage"));
                                }
                            }
                        });
                    }
                    return {
                        _init: function (o) {
                            init();
                        }
                    }
                }

                if ($(".fm01.eloqua-container").length > 0) {
                    eloqueForms()._init();
                }

                if ($J(".eloqua-ajax-frm") && $J(".eloqua-ajax-frm").length > 0) {
                    //var form = $J("#eloqua-ajax-frm");
                    //var formName = $J(form).attr('data-form-name');

                    $J(window).load(function () {
                        $J("form.eloqua-ajax-frm input:checkbox").each(function () {
                            fixHiddenCheckField(this);
                        });

                        $J("form.eloqua-ajax-frm input:checkbox").change(function () {
                            fixHiddenCheckField(this);
                        });
                    });

                    function fixHiddenCheckField(checkField) {
                        var currentForm = $J(checkField).closest('form');
                        var name = $J(checkField).attr("name");
                        var hiddenSelector = "input:hidden[name=" + name + "]";
                        var checkBoxesInListSelector = "input:checkbox[name=" + name + "]";
                        var checkedCheckBoxesInListSelector = "input:checked[name=" + name + "]";

                        if ($J(currentForm).find(checkedCheckBoxesInListSelector).length >= 1 || $J(currentForm).find(checkBoxesInListSelector).length > 1) {
                            $J(currentForm).find("input").remove(hiddenSelector);
                        }
                        else {
                            if ($J(currentForm).find(hiddenSelector).length === 0) {
                                $J(currentForm).append("<input type='hidden' name='" + name + "' value='false' />");
                            }
                        }
                    }

                    $J('form.eloqua-ajax-frm .datepicker').datepicker({ dateFormat: 'yy-mm-dd' });
                    $J(".eloqua-hidden-div").empty();

                    $J('.eloqua-ajax-frm').each(function () {
                        var confirmationMessage = '';
                        var $currentForm = $J(this);
                        confirmationMessage = $currentForm.data('eloqua-confirmation-message');
                        $currentForm.closest('.eloqua-container').find(".eloqua-hidden-div").html(confirmationMessage);
                    });

                    function eloqueValidateForm(currentForm) {
                        var isValid = true;
                        currentForm.find("input").each(function () {
                            if ($(this).attr("required") === "required" && $(this).val().length < 1 && $(this).next().is(".form-feedback")) {
                                $(this).addClass("error");
                                $(this).next().addClass("error").find("span").text($(this).attr("emptymessage"));
                                isValid = false;
                            }
                            if ($(this).is(':checkbox') && $(this).attr("required") == 'required' && !$(this).prop('checked') && $(this).parent().parent().parent().find(".form-feedback")) {

                                $(this).addClass("error");
                                $(this).parent().parent().parent().find(".form-feedback").addClass("error").find("span").text($(this).attr("emptymessage"));
                                isValid = false;
                            }
                            if ($(this).attr("isemail")) {
                                var re = new RegExp($(this).attr("pattern"));
                                if (!re.test($(this).val())) {
                                    $(this).addClass("error");
                                    $(this).next().addClass("error").find("span").text($(this).attr("emailmessage"));
                                    isValid = false;
                                }
                            }
                            if (isValid) {
                                var fieldValLength = $(this).val().length;
                                if ($(this).attr("maxlength") && fieldValLength > $(this).attr("maxlength")) {
                                    $(this).addClass("error");
                                    $(this).next().addClass("error").find("span").text($(this).attr("lengthmessage"));
                                    isValid = false;
                                }
                                if ($(this).attr("minlength") && fieldValLength < $(this).attr("minlength")) {
                                    $(this).addClass("error");
                                    $(this).next().addClass("error").find("span").text($(this).attr("lengthmessage"));
                                    isValid = false;
                                }
                            }
                        });
                        currentForm.find("select").each(function () {
                            if ($(this).attr("required") === "required" && $(this).prop("selectedIndex") < 1 && $(this).parent().parent().find(".form-feedback")) {
                                $(this).addClass("error");
                                $(this).parent().parent().find(".form-feedback").addClass("error").find("span").text($(this).attr("emptymessage"));
                                isValid = false;
                            }
                        });

                        return isValid;
                    }

                    $J(".eloqua-check-box input:checkbox").change(function () {
                        if ($(this).attr("required") === "required" && $(this).parent().parent().parent().find(".form-feedback")) {

                            if ($(this).prop('checked')) {
                                $(this).removeClass("error");
                                $(this).parent().parent().parent().find(".form-feedback").removeClass("error");
                            }
                            else {
                                $(this).addClass("error");
                                $(this).parent().parent().parent().find(".form-feedback").addClass("error").find("span").text($(this).attr("emptymessage"));
                            }
                        }

                    });

                    //FOR CP19 FORM ONLY
                    $J('#country').change(function () {
                        var country = $J('#country').val();

                        if (country) {
                            country = country.toLowerCase();

                            if (country == "australia" || country == "au") {
                                $J('#stateOrTerritoryAU1').closest(".field").show();
                                $("#stateOrTerritoryAU1").attr("required", "required");

                            }
                            else {
                                $J('#stateOrTerritoryAU1').closest(".field").hide();
                                $("#stateOrTerritoryAU1").val('');
                                $("#stateOrTerritoryAU1").removeAttr("required");
                            }
                        }

                    });

                    $J('.eloqua-submit').click(function (event) {
                        event.preventDefault();
                        canonHelper.showSpinner();
                        var currentForm = $J(this).closest('form');
                        // TODO: setup in app settings
                        var apiBaseUrl = $J(currentForm).attr('data-api-url');
                        // TODO: Form validation                        
                        if (eloqueValidateForm(currentForm) && currentForm.valid()) {
                            $J(this)[0].disabled = true;
                            var queryString = $J(currentForm).serialize();
                            submitEloquaForm(apiBaseUrl, currentForm, queryString);
                        }
                        else {
                            canonHelper.hideSpinner();
                        }

                    });


                    $J('.close').click(function (event) {
                        var ecrmContainer = $J('.ecrm__trigger-form');
                        if (ecrmContainer && ecrmContainer.length > 0) {
                            var eloquasubmit = $J("#eloquasubmit").val();
                            if (eloquasubmit == '1') {
                                ecrmContainer.hide();
                            }
                        }

                    });

                    function submitEloquaForm(apiBaseUrl, currentForm, queryString) {

                        var ajaxUrl = apiBaseUrl + $J(currentForm).attr("action") + '?' + queryString;
                        $J.ajax({
                            type: 'POST',
                            url: ajaxUrl,
                            contentType: 'application/json',
                            beforeSend: function (xhr) {
                                xhr.setRequestHeader('Source', 'canon');
                            },
                            error: function (request, status, error) {
                                onError(request, status, error, $J(currentForm));
                            }
                        }).done(function (response) {
                            if (response.Status === "OK") {
                                showHide($J(currentForm));

                                //  GTM integration
                                window.dataLayer = window.dataLayer || []
                                window.dataLayer.push({
                                    'event': 'formSubmission',
                                    'formId': $('#FormId').val(),
                                    'formURL': window.location.href,
                                    'formName': $('#elqFormName').val()
                                });
                            }

                            else {
                                $J(this)[0].disabled = false;
                                onError(null, null, null, $J(currentForm));
                            }
                        });

                    }

                    function onError(xhr, errorType, exception, currentForm) {
                        canonHelper.hideSpinner();
                        $J(currentForm).find('.eloqua-submit')[0].disabled = false;
                        $J('.global-error-message-body').html("<p>Sorry! We are experiencing technical difficulties, please contact support team.</p>");
                        var modelInst = $('[data-remodal-id=globalErrorMessage]').remodal();
                        modelInst.open();
                    }

                    function showHide(currentForm) {
                        canonHelper.hideSpinner();
                        if ($J(currentForm).closest(".cp19") != undefined && $J(currentForm).closest(".cp19").length > 0) {
                            //FOR CP19 FORM ONLY
                            defaultFunctions.downloadResourceFormOnSubmit(currentForm);
                        }
                        else if ($J(currentForm).closest(".eloqu-subscription-with-header") != undefined && $J(currentForm).closest(".eloqu-subscription-with-header").length > 0) {
                            //FOR eloqu-subscription FORM ONLY
                            var messageContainer = $J('.eloqu-subscription-with-header-container');
                            if (messageContainer && messageContainer.length > 0) {
                                console.log(messageContainer.find(".eloqua-hidden-div"));
                                messageContainer.find(".eloqua-hidden-div").show();
                                $J("#eloqua-hidden-div").css('display', 'block');
                                messageContainer.find(".eloqua-message").show();
                                messageContainer.find(".eloqua-message").css('display', 'block');
                                $('html, body').animate({
                                    scrollTop: messageContainer.find(".eloqua-message").offset().top - $J(currentForm).closest(".eloqua-container").height() - 350
                                }, 1000);

                                $J("#eloqu-subscription").hide();
                                $J(currentForm)[0].reset();

                                if ($J(currentForm).closest(".eloqu-subscription-with-header") != undefined && $J(currentForm).closest(".eloqu-subscription-with-header").length > 0) {
                                    var redirect = $J("#RedirectLink").val();

                                    if (redirect != undefined && redirect.length > 0) {
                                        var count = $J("#redirect-count").val();
                                        setTimeout(
                                            function () {
                                                window.location.href = redirect;
                                                //console.log('Working')
                                            }, 10000);
                                    }

                                    var innterval = setInterval(function () {
                                        if (count == 0)
                                            clearInterval(innterval);
                                        count--;
                                        if (count >= 0) {
                                            $("#redirect-count-display").html('You will be redirect in ' + count + ' seconds.');
                                        }


                                    }, 1000);
                                }

                            }

                        }
                        else {
                            //FOR ALL ELOQUA FORMs ONLY
                            var messageContainer = $J(currentForm).closest('.eloqua-container');
                            if (messageContainer.length > 0) {
                                messageContainer.find(".eloqua-hidden-div").show();
                                messageContainer.find(".eloqua-message").show();
                                messageContainer.find(".eloqua-message").css('display', 'block');
                                $('html, body').animate({
                                    scrollTop: messageContainer.find(".eloqua-message").offset().top - $J(currentForm).closest(".eloqua-container").height() - 70
                                }, 1000);
                            }
                            $J(currentForm).hide();
                            $J(currentForm)[0].reset();

                            if ($J(currentForm).closest(".ecrm__trigger-form") != undefined && $J(currentForm).closest(".ecrm__trigger-form").length > 0) {
                                $J("#eloquasubmit").val('1');
                                setTimeout(
                                    function () {
                                        $J('.ecrm__trigger-form').hide();
                                        //console.log('Working')
                                    }, 5000);

                            }
                        }
                    }
                }
            },

            initClaBookingAccordion: function () {
                var $scope = $(".cf16");
                function init() {
                    if ($scope.length > 0) {
                        $scope.find(".the-farm").each(function () {
                            var farmComp = $J(this);
                            farmComp.addClass("container");
                            farmComp.addClass("content");
                            farmComp.removeClass("the-farm");
                            var tile = $J(this).find(".tile--102");
                            if (tile.length > 0) {
                                var $index = 0;
                                tile.each(function () {
                                    $J(this).addClass("tile--103");
                                    $J(this).removeClass("tile--102");
                                    if ($index > 0) {
                                        $J(this).removeClass("margin--l0");
                                    }
                                    $index++;
                                });
                            }
                        });
                    }
                }
                init();
            },

            initLightAwardsSubmission: function () {
                var $liveSubmissionContainer = $J('.cla-submission');
                if ($liveSubmissionContainer && $liveSubmissionContainer.length > 0) {

                    //Input validation
                    function validateForm(container) {
                        var formValid = true;
                        var $submitButton = container.find("button");
                        container.find('input,.textarea-input').each(function () {
                            if (!$J(this)[0].checkValidity() || $J(this).hasClass('invalid')) {
                                formValid = false;
                            }

                        }).promise().done(function () {
                            if (formValid) {
                                if (!$J($submitButton).hasClass('valid')) {
                                    $J($submitButton).addClass('valid');
                                    $J($submitButton).removeAttr('disabled');
                                }
                            }
                            else {
                                $J($submitButton).removeClass('valid');
                                $J($submitButton).attr('disabled', 'disabled');
                            }
                        });
                    }

                    function navigateScreenToTop() {
                        $('html, body').animate({
                            scrollTop: $(".charity-cashback-wizard") - $("header").height()
                        }, 1000);
                    }

                    //Step 1
                    var $step1Form = $liveSubmissionContainer.find('form.cla-submission-step1');
                    if ($step1Form && $step1Form.length > 0) {
                        validateForm($step1Form);
                        //Validate ticket number
                        var $validateTicketButton = $step1Form.find('.validate-ticket');
                        if ($validateTicketButton && $validateTicketButton.length > 0) {
                            var $fieldValidationContainer = $step1Form.find('.field-validation-valid');
                            var $ticketValidationMessageContainer = $step1Form.find('.ticket-validation-valid');

                            function showInvalidTicketErrorMessage() {
                                $fieldValidationContainer.addClass('error');
                                $ticketValidationMessageContainer.addClass('error');
                            }

                            function hideInvalidTicketErrorMessage() {
                                $fieldValidationContainer.removeClass('error');
                                $ticketValidationMessageContainer.removeClass('error');
                            }

                            var $ticketInput = $step1Form.find('#ticket');
                            if ($ticketInput && $ticketInput.length > 0) {
                                $ticketInput.off('input');
                                $ticketInput.on('input', function () {
                                    if ($J(this).val().length === parseInt($J(this).attr('maxlength'))) {
                                        $validateTicketButton.removeAttr('disabled');
                                    }
                                    else if (!$validateTicketButton.attr('disabled')) {
                                        $validateTicketButton.attr('disabled', 'disabled');
                                    }
                                    hideInvalidTicketErrorMessage();
                                });
                            }

                            var $templateOnSucceed = $liveSubmissionContainer.find('.live-submission-step1-template');

                            $validateTicketButton.off('click');
                            $validateTicketButton.on('click', function (e) {
                                e.preventDefault();
                                canonHelper.showSpinner();
                                var token = canonHelper.getQueryString("token");
                                var ticketNumber = $ticketInput.val();

                                var postData = {
                                    token: token,
                                    ticketNumber: ticketNumber
                                };

                                var data = canonHelper.addAntiForgeryToken(postData);
                                var post = $.post('/cla/lightawards/validateticket', data);

                                post.done(function (data) {
                                    if (data) {
                                        if (data.IsSuccessful && data.EmailAddress) {
                                            hideInvalidTicketErrorMessage();

                                            var lineToReplace = $step1Form.find('.onsucceed-replacement');
                                            $J(lineToReplace).replaceWith($templateOnSucceed.html()).promise().done(function () {
                                                $step1Form.find('#email').val(data.EmailAddress);
                                                var $continueButton = $step1Form.find('button.continue');
                                                $continueButton.off('click');
                                                $continueButton.on('click', function (el) {
                                                    el.preventDefault();
                                                    canonHelper.showSpinner();
                                                    var token = canonHelper.getQueryString("token");
                                                    var ticketCode = $ticketInput.val();

                                                    var postData = {
                                                        token: token,
                                                        ticketCode: ticketCode
                                                    };

                                                    var data = canonHelper.addAntiForgeryToken(postData);
                                                    var post = $.post('/cla/lightawards/step1ticketvalidation', data);

                                                    post.done(function (data) {
                                                        if (data) {
                                                            if (data.IsSuccessful != undefined && !data.IsSuccessful && data.Message) {
                                                                showGenericErrorModal(data.Message);
                                                            }
                                                            else {
                                                                $J($liveSubmissionContainer).html(data);
                                                            }

                                                            defaultFunctions.initLightAwardsSubmission();
                                                            canonHelper.hideSpinner();
                                                        }
                                                    });

                                                    post.fail(function () {
                                                        canonHelper.hideSpinner();
                                                        showGenericErrorModal();
                                                    });
                                                });
                                            });

                                            defaultFunctions.initLightAwardsSubmission();
                                        }
                                        else {
                                            showInvalidTicketErrorMessage();
                                        }

                                        canonHelper.hideSpinner();
                                    }
                                    else {
                                        canonHelper.hideSpinner();
                                        showInvalidTicketErrorMessage();
                                    }
                                });

                                post.fail(function () {
                                    canonHelper.hideSpinner();
                                    showInvalidTicketErrorMessage();
                                });
                            });

                        }
                    }

                    //Step 2
                    var $step2Form = $liveSubmissionContainer.find('.cla-submission-step2');
                    if ($step2Form && $step2Form.length > 0) {
                        $step2Form.find('#myCLAImage').off('change');
                        $step2Form.find('#myCLAImage').on('change', function () {
                            var $validationMessage = $J(this).closest('.field').find(".field-validation-valid");
                            var $placeholder = $J(this).closest('.field').find(".after");
                            var file = $J(this)[0].files[0];
                            var fileSize = file.size / 1048576;

                            var $submitButton = $step2Form.find("button");

                            if (fileSize > 5) {
                                if (!$J(this).hasClass('invalid')) {
                                    $J(this).addClass('invalid');
                                }

                                if (!$validationMessage.hasClass('error')) {
                                    $validationMessage.addClass('error');
                                }
                            }
                            else {
                                $J(this).removeClass('invalid');
                                $validationMessage.removeClass('error');
                            }

                            $placeholder.text(file.name);
                            validateForm($step2Form);
                        });

                        $step2Form.find('input,.textarea-input').off('input');
                        $step2Form.find('input,.textarea-input').on('input', function () {
                            validateForm($step2Form);
                        });

                        $step2Form.find('input:not([type="file"])').off('change');
                        $step2Form.find('input:not([type="file"])').on('change', function () {
                            validateForm($step2Form);
                        });

                        $step2Form.submit(false);

                        var $continueButton = $step2Form.find('button.continue');
                        $continueButton.off('click');
                        $continueButton.on('click', function (e) {
                            e.preventDefault();
                            var $recaptcha = $step2Form.find('#claCaptcha');
                            if ($recaptcha.hasClass('invalid')) {
                                var $validationMessage = $recaptcha.closest('.field').find('.field-validation-valid');
                                if (!$validationMessage.hasClass('error')) {
                                    $validationMessage.addClass('error');
                                }
                            }
                            else {
                                canonHelper.showSpinner();
                                var data = new FormData($step2Form.get(0));
                                var token = canonHelper.getQueryString("token");
                                data.append("token", token);
                                data.append("Photo", $step2Form.find('#myCLAImage')[0].files[0]);
                                var description = $step2Form.find('.textarea-input').val();
                                data.append("description", description);

                                $.ajax({
                                    type: 'POST',
                                    url: '/cla/lightawards/step2uploadimage',
                                    data: data,
                                    contentType: false,
                                    processData: false,
                                    cache: false,
                                    success: function (data) {
                                        if (data) {
                                            if (data.IsSuccessful != undefined && !data.IsSuccessful && data.Message) {
                                                showGenericErrorModal();
                                            }
                                            else {
                                                $J($liveSubmissionContainer).html(data).promise().done(function () {
                                                    defaultFunctions.initLightAwardsSubmission();
                                                    navigateScreenToTop();
                                                });
                                            }
                                            canonHelper.hideSpinner();
                                        }
                                        else {
                                            canonHelper.hideSpinner();
                                            showGenericErrorModal();
                                        }
                                    },
                                    error: function () {
                                        canonHelper.hideSpinner();
                                        showGenericErrorModal();
                                    }
                                });
                            }
                        });
                    }

                    //Go back
                    var $goBackButton = $liveSubmissionContainer.find('.goback');
                    if ($goBackButton && $goBackButton.length > 0) {
                        $goBackButton.off('click');
                        $goBackButton.on('click', function (e) {
                            e.preventDefault();
                            canonHelper.showSpinner();
                            var token = canonHelper.getQueryString("token");
                            var postData = {
                                token: token
                            };
                            var data = canonHelper.addAntiForgeryToken(postData);
                            var post = $.post('/cla/lightawards/goback', data);
                            post.done(function (data) {
                                if (data) {
                                    if (data.IsSuccessful != undefined && !data.IsSuccessful && data.Message) {
                                        showGenericErrorModal(data.Message);
                                    }
                                    else {
                                        $J($liveSubmissionContainer).html(data);
                                    }

                                    defaultFunctions.initLightAwardsSubmission();
                                    canonHelper.hideSpinner();
                                }
                            });
                            post.fail(function () {
                                canonHelper.hideSpinner();
                                showGenericErrorModal();
                            });
                        });
                    }
                }

                function showGenericErrorModal(message) {
                    var errorMessage = message ? message : "Sorry! We are experiencing technical difficulties, please contact our support team.";
                    $J('.global-error-message-body').html("<p>" + errorMessage + "</p>");
                    var modelInst = $('[data-remodal-id=globalErrorMessage]').remodal();
                    modelInst.open();
                }
            },

            initOnFormSubmissionErrorMessage: function () {
                var headerHeight;
                var scrollposition;
                var reposition = function () {
                    headerHeight || (headerHeight = jQuery('.sticky--fixed').outerHeight() + 20);
                    setTimeout(function () {
                        window.scrollBy(0, -headerHeight);
                    }, 50);
                    scrollposition = $(window).scrollTop() - 90;
                };

                jQuery(document).on('click', 'form :submit', function (e) {
                    var form;
                    if ((form = jQuery(e.target).closest('form')).length !== 1) {
                        return;
                    }
                    if (!form[0].checkValidity || form[0].checkValidity()) {
                        return;
                    }
                    if ($(window).scrollTop() != scrollposition) {
                        reposition();
                    }
                });
                var ua = window.navigator.userAgent;
                var msie = ua.indexOf("MSIE ");

                if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer, return version number
                {

                    jQuery(document).on('focus', '.dpicker', function (e) {
                        if ($(this).attr("required")) {
                            $(this).removeAttr("required");
                            $(this).attr("data-isrequired", "true");
                        }
                    });
                    jQuery(document).on('blur', '.dpicker', function (e) {
                        if ($(this).attr("data-isrequired")) {
                            $(this).removeAttr("data-isrequired");
                            $(this).attr("required", "true");
                        }
                    });
                }
                $('input[type="email"]').each(function () {
                    $(this)[0].setCustomValidity('Please enter valid email');
                });
            },

            bynderGallery: function () {
                var $swipeBoxIndex = 0;
                var imgArray = [];
                var bynderGalleryData = "";
                var bynderGalleryFilteredData = "";
                var $galleryPageSize = 20;
                var $galleryPageIndex = 0;
                var $galleryTotalItemCount = 0;
                var $totalItemsDisplayed = 0;
                var $itemsLeftToDisplayed = 0;
                var $isNextPageAvailable = false;

                function searchItemsBySelectedTags(selectedTags, source) {
                    //var selectedFilter = {isPrimary:primary,Id:id,tags:[],count:0,name:''}//

                    var searchResult = [];

                    if (selectedTags && source && source.length > 0) {
                        searchResult = $.grep(source, function (item) {

                            var result = item && item.Tags;


                            $.each(selectedTags, function (index, filter) {

                                var foundInFilter = $.grep(item.Tags, function (tag) {
                                    return ($.inArray(tag, filter.tags) >= 0);
                                }).length > 0;

                                result = result && foundInFilter;
                                return result;
                            });
                            return result;
                        });
                        return searchResult;
                    }

                    return source;
                }

                function renderGalleryTiles(response, componentContainer) {
                    var loadMoreButtonContainer = $J(componentContainer).parent().find(".bynder-gallery-feed-load-more");
                    var template = $J(componentContainer).find('.bynder-gallery-feed-container-template').html();
                    var resultContainer = $J(componentContainer).find(".bynder-gallery-feed-container");
                    var noResultsFoundContainer = $J(componentContainer).find(".no-result-found-container");
                    bynderGalleryFilteredData = "";
                    $galleryPageIndex = 0;
                    $galleryTotalItemCount = 0;
                    $totalItemsDisplayed = 0;
                    $itemsLeftToDisplayed = 0;
                    $isNextPageAvailable = false;
                    if (!noResultsFoundContainer.hasClass("hide--me")) {
                        noResultsFoundContainer.addClass("hide--me");
                    }
                    if (!loadMoreButtonContainer.hasClass("hide--me")) {
                        loadMoreButtonContainer.addClass("hide--me");
                    }
                    if (response && response.length > 0) {
                        $galleryTotalItemCount = response.length;
                        bynderGalleryFilteredData = response;
                        var tiles = response.slice(0, Math.min($galleryTotalItemCount, $galleryPageSize));
                        if (tiles) {
                            var result = Mustache.to_html(template, { "Media": tiles });
                            $totalItemsDisplayed = Math.min($galleryTotalItemCount, (($galleryPageIndex + 1) * $galleryPageSize));
                            $itemsLeftToDisplayed = $galleryTotalItemCount - $totalItemsDisplayed;
                            $isNextPageAvailable = $itemsLeftToDisplayed > 0;
                            $J(resultContainer).html(result);
                        }
                    }
                    else {
                        $J(resultContainer).html("");
                        if (noResultsFoundContainer.hasClass("hide--me")) {
                            noResultsFoundContainer.removeClass("hide--me");
                        }
                    }
                    loadMoreButtonContainer.find("a").data("is-next-page-available", $isNextPageAvailable);
                    if ($isNextPageAvailable) {
                        loadMoreButtonContainer.removeClass("hide--me");
                        loadMoreButtonContainer.find("a").data("current-page", $galleryPageIndex);
                        loadMoreButtonContainer.find("a").html("<span>Load more entries</span><br />(" + $itemsLeftToDisplayed + " entries left)");
                    }
                }

                function loadGalleryOnFilter(selectedTags, componentContainer) {
                    canonHelper.showSpinner();
                    var data = {};
                    if (selectedTags && selectedTags.length > 0) {
                        data = searchItemsBySelectedTags(selectedTags, bynderGalleryData);
                    }
                    else {
                        data = bynderGalleryData;
                    }
                    renderGalleryTiles(data, componentContainer);
                    canonHelper.hideSpinner();
                };

                function galleryPagination(pageIndex, componentContainer) {
                    canonHelper.showSpinner();
                    var data = bynderGalleryFilteredData;
                    var loadMoreButtonContainer = $J(componentContainer).parent().find(".bynder-gallery-feed-load-more");
                    var template = $J(componentContainer).find('.bynder-gallery-feed-container-template').html();
                    var resultContainer = $J(componentContainer).find(".bynder-gallery-feed-container");
                    var noResultsFoundContainer = $J(componentContainer).find(".no-result-found-container");
                    if (!noResultsFoundContainer.hasClass("hide--me")) {
                        noResultsFoundContainer.addClass("hide--me");
                    }
                    loadMoreButtonContainer.addClass("hide--me");
                    $isNextPageAvailable = false;
                    if (data && data.length > 0) {
                        var response = data.slice($totalItemsDisplayed, $totalItemsDisplayed + Math.min($galleryTotalItemCount, $galleryPageSize));
                        var result = Mustache.to_html(template, { "Media": response });
                        $totalItemsDisplayed = Math.min($galleryTotalItemCount, ((pageIndex + 1) * $galleryPageSize));
                        $itemsLeftToDisplayed = $galleryTotalItemCount - $totalItemsDisplayed;
                        $isNextPageAvailable = $itemsLeftToDisplayed > 0;
                        $J(resultContainer).append(result);
                    }
                    else {
                        $J(resultContainer).html("");
                        if (noResultsFoundContainer.hasClass("hide--me")) {
                            noResultsFoundContainer.removeClass("hide--me");
                        }
                    }

                    loadMoreButtonContainer.find("a").data("is-next-page-available", $isNextPageAvailable);
                    if ($isNextPageAvailable) {
                        loadMoreButtonContainer.removeClass("hide--me");
                        loadMoreButtonContainer.find("a").data("current-page", pageIndex);
                        loadMoreButtonContainer.find("a").html("<span>Load more entries</span><br />(" + $itemsLeftToDisplayed + " entries left)");
                    }

                    canonHelper.hideSpinner();
                }

                function updateFilters($componentContainer, $selectField) {
                    if ($selectField == undefined || !$selectField) return;

                    var filters = "";
                    var allTags = getAllFilterTags($componentContainer);
                    var selectedId = $selectField.attr("id");
                    var findSelectedTags = $.grep(allTags, function (item) { return item.Id === selectedId });
                    var selectedFilter = findSelectedTags && findSelectedTags.length > 0 ? findSelectedTags : allTags;


                    var isSecondaryFilterSelected = $selectField != undefined && $selectField && !$selectField.hasClass("primary");
                    if (isSecondaryFilterSelected) {
                        filters = $J($componentContainer).find(".bynder-gallery-filter.secondary[id != '" + $selectField.attr("id") + "']");
                    }
                    else {
                        filters = $J($componentContainer).find(".bynder-gallery-filter.secondary");

                    }

                    if (filters.length > 0) {
                        var filterOptions = [];
                        filters.each(function () {
                            var $this = $J(this);
                            var currentId = $this.attr("id");
                            $this.find("option").each(function () {
                                if ($J(this).val() !== "") {
                                    filterOptions.push({
                                        isPrimary: false,
                                        Id: currentId,
                                        tags: $J(this).val().indexOf(",") > -1 ? $J(this).val().split(',') : [$J(this).val()],
                                        count: 0,
                                        name: $J(this).data("text")
                                    })
                                }
                            });
                        });

                        if (isSecondaryFilterSelected && $selectField != undefined && $selectField) {
                            $componentContainer.find(".bynder-gallery-filter.secondary[id != '" + $selectField.attr("id") + "'] option").hide();
                            $componentContainer.find(".bynder-gallery-filter.secondary[id != '" + $selectField.attr("id") + "'] option").attr("disabled");
                            $componentContainer.find(".bynder-gallery-filter.secondary[id != '" + $selectField.attr("id") + "'] option:first-child").show();
                            $componentContainer.find(".bynder-gallery-filter.secondary[id != '" + $selectField.attr("id") + "'] option:first-child").removeAttr("disabled");
                        }
                        else {
                            $componentContainer.find(".bynder-gallery-filter.secondary option").hide();
                            $componentContainer.find(".bynder-gallery-filter.secondary option").attr("disabled");
                            $componentContainer.find(".bynder-gallery-filter.secondary option:first-child").show();
                            $componentContainer.find(".bynder-gallery-filter.secondary option:first-child").removeAttr("disabled");
                        }

                        if (filterOptions.length > 0) {
                            $.each(filterOptions, function (i, item) {
                                if (item && item.tags) {


                                    var currentFilters = selectedFilter && selectedFilter.length > 0 ? $.merge([item], selectedFilter) : [item];
                                    var response = searchItemsBySelectedTags(currentFilters, bynderGalleryData);
                                    item.count = response && response.length > 0 ? response.length : 0;

                                    if (item.count > 0) {
                                        if (isSecondaryFilterSelected && $selectField != undefined && $selectField) {
                                            $componentContainer.find(".bynder-gallery-filter.secondary[id != '" + $selectField.attr("id") + "'] option[data-text='" + item.name + "']").show();
                                            $componentContainer.find(".bynder-gallery-filter.secondary[id != '" + $selectField.attr("id") + "'] option[data-text='" + item.name + "']").removeAttr("disabled");
                                        }
                                        else {
                                            $componentContainer.find(".bynder-gallery-filter.secondary option[data-text='" + item.name + "']").show();
                                            $componentContainer.find(".bynder-gallery-filter.secondary option[data-text='" + item.name + "']").removeAttr("disabled");
                                        }
                                    }
                                }
                            });
                        }
                    }
                }

                function getAllFilterTags($componentContainer) {
                    var componentContainer = $J($componentContainer);

                    var selectedFilters = [];
                    var filters = componentContainer.find(".bynder-gallery-filter");
                    filters.each(function () {
                        var $this = $J(this);
                        var id = $(this).attr('id');
                        var tags = [];
                        if (id != undefined) {
                            var primary = $(this).hasClass("primary");
                            var selectedFilter = {
                                isPrimary: primary,
                                Id: id,
                                tags: [],
                                count: 0,
                                name: ''
                            };
                            $this.find("option:checked").each(function () {
                                if ($J(this).val() !== "") {

                                    var val = $J(this).val();
                                    var tags = val.length > 0 ? val.split(',') : [];

                                    if (tags.length > 0) {
                                        selectedFilter.tags = tags.distinct();
                                        selectedFilters.push(selectedFilter);
                                    }

                                    return false;
                                }
                            });
                        }
                    });
                    return selectedFilters;
                }

                if ($J(".bynder-gallery-filter.primary").length > 0) {
                    $J(".bynder-gallery-filter.primary").off("change");
                    $J(".bynder-gallery-filter.primary").on("change", function (e) {
                        e.preventDefault();
                        e.stopPropagation();
                        var $this = $J(this);
                        var $componentContainer = $this.closest(".bynder-gallery-feed");
                        var isSecondaryFilterExists = $componentContainer.find(".bynder-gallery-filter.secondary").length > 0;
                        if (isSecondaryFilterExists) {
                            $componentContainer.find(".bynder-gallery-filter.secondary").prop('selectedIndex', 0);
                            $componentContainer.find(".bynder-gallery-filter.secondary option:first-child").hide();
                            $componentContainer.find(".bynder-gallery-filter.secondary option:first-child").prop("disabled", "true");
                        }
                        var selectedTags = getAllFilterTags($componentContainer);
                        loadGalleryOnFilter(selectedTags, $componentContainer);
                        if (isSecondaryFilterExists) { updateFilters($componentContainer, $this); }
                    });
                }

                if ($J(".bynder-gallery-filter.secondary").length > 0) {
                    $J(".bynder-gallery-filter.secondary").off("change");
                    $J(".bynder-gallery-filter.secondary").on("change", function (e) {
                        e.preventDefault();
                        e.stopPropagation();
                        var $this = $J(this);
                        var $componentContainer = $this.closest(".bynder-gallery-feed");
                        var isMoreSecFilterExists = $componentContainer.find(".bynder-gallery-filter.secondary").length > 1;
                        var selectedTags = getAllFilterTags($componentContainer);
                        loadGalleryOnFilter(selectedTags, $componentContainer);
                        if (isMoreSecFilterExists) { updateFilters($componentContainer, $this); }
                    });
                }

                if ($J(".bynder-gallery-feed-load-more").length > 0) {
                    $J(".bynder-gallery-feed-load-more a").off("click");
                    $J(".bynder-gallery-feed-load-more a").on("click", function (e) {
                        e.preventDefault();
                        e.stopPropagation();
                        var $this = $J(this);
                        var $componentContainer = $this.parent().parent().find(".bynder-gallery-feed");
                        var isNextPageAvailable = $this.data("is-next-page-available");
                        var prevPageIndex = $this.data("current-page");
                        if (isNextPageAvailable) {
                            galleryPagination(prevPageIndex + 1, $componentContainer);
                        }
                    });
                }

                function gallery() {
                    var $scope = $('.cf17');

                    function handleNextSlide() {
                        if ($(".bynder-gallery-feed ul:has(li)").length > 0) {
                            $swipeBoxIndex = $('#swipebox-slider .slide').index($('#swipebox-slider .slide.current'));
                            var lastIndex = $(".bynder-gallery-feed ul li:last-child").data('id');
                            if (lastIndex === $swipeBoxIndex && ($(".bynder-gallery-feed-load-more a").data('is-next-page-available') === true || $(".bynder-gallery-feed-load-more a").data('is-next-page-available') === "True")) {
                                if ($J("#swipebox-next").hasClass("disabled")) {
                                    $J("#swipebox-next").removeClass("disabled");
                                }
                                $(".bynder-gallery-feed-load-more a").trigger("click");
                            }

                            if (lastIndex === undefined) {
                                canonHelper.showSpinner();
                                $J("#swipebox-close").trigger("click");
                                $scope.find(".gallery ul li[data-id=" + $swipeBoxIndex + "]").trigger("click");
                                setTimeout(function () {
                                    $J("#swipebox-next").trigger("click");
                                    canonHelper.hideSpinner();
                                    $J("#swipebox-overlay").show();
                                }, 500);
                            }
                        }
                    }

                    function keyboard() {
                        var $this = this;
                        $(window).bind('keyup', function (event) {
                            event.preventDefault();
                            event.stopPropagation();
                            if (event.keyCode === 39) {
                                handleNextSlide();
                            }
                        });
                    }

                    function afterOpen() {
                        $('body').addClass('swipebox');
                        $J("#swipebox-next").on('click', function () {
                            handleNextSlide();
                        });
                        keyboard();
                    }

                    function afterClose() {
                        var slide = $(".cf17 ul li[data-id=" + $swipeBoxIndex + "]");
                        $('html, body').animate({
                            scrollTop: slide.offset().top - 50
                        }, 1000);
                    }

                    function moveSlide() {
                        $swipeBoxIndex = $('#swipebox-slider .slide').index($('#swipebox-slider .slide.current'));
                    }

                    function initSwipeBox() {
                        $scope.find('.gallery ul').on('click', 'li', function (a, b) {
                            imgArray = [];
                            var title = '';
                            $scope.find('.gallery ul li').each(function (a, b) {
                                title = "<p class='jig-caption-title'>" + $(this).data('copyright') + '</p><p class="jig-caption-description">' + $(this).data('desc') + '</p>';
                                bg = $(this).data('original-image-url');
                                bg = bg.replace(/.*\s?url\([\'\"]?/, '').replace(/[\'\"]?\).*/, '');
                                $(this).attr('data-id', a);
                                imgArray.push({ "href": bg, "title": title });
                            });
                            bg = $(this).data('original-image-url');
                            bg = bg.replace(/.*\s?url\([\'\"]?/, '').replace(/[\'\"]?\).*/, '');
                            $.swipebox(imgArray, {
                                initialIndexOnArray: parseInt($(this).attr("data-id")),
                                hideBarsDelay: 60000,
                                afterOpen: function () { afterOpen() },
                                afterClose: function () { afterClose(); },
                                nextSlide: function () { moveSlide(); },
                                prevSlide: function () { moveSlide(); }
                            });

                            handleNextSlide();
                        });
                    }

                    function init() {
                        var componentContainer = $J(".bynder-gallery-feed");
                        if (componentContainer != undefined && componentContainer.length <= 0) return;
                        var collectionId = $J(componentContainer).data("collection-id");
                        var getBynderGallery = $.get("/content-tile/gallery/getbyndergallerydata?collectionId=" + collectionId);
                        var resultContainer = $J(componentContainer).find(".bynder-gallery-feed-container");
                        var noResultsFoundContainer = $J(componentContainer).find(".no-result-found-container");
                        canonHelper.showSpinner();
                        getBynderGallery.done(function (data) {
                            bynderGalleryData = "";
                            if (data && data.Payload && data.Payload.Media && data.Payload.Media.length > 0) {
                                bynderGalleryData = data.Payload.Media;
                                var selectedTags = getAllFilterTags(componentContainer);
                                loadGalleryOnFilter(selectedTags, componentContainer);
                                if (selectedTags && selectedTags.length > 0) {
                                    componentContainer.find(".bynder-gallery-filter").each(function () {
                                        if ($J(this).prop('selectedIndex') > 0) {
                                            updateFilters(componentContainer, $J(this));
                                        }
                                    });
                                }
                                else {
                                    updateFilters(componentContainer);
                                }
                            }
                            else {
                                $J(resultContainer).html("");
                                if (noResultsFoundContainer.hasClass("hide--me")) {
                                    noResultsFoundContainer.removeClass("hide--me");
                                }
                            }
                            initSwipeBox();
                            canonHelper.hideSpinner();
                        });

                        getBynderGallery.fail(function () {
                            canonHelper.hideSpinner();
                        });
                    }

                    return { _init: function () { init(); } }
                }

                if ($('.cf17').length > 0) {
                    gallery()._init();
                }
            }
        };

        Array.prototype.hasValue = function (v) {
            for (var i = 0; i < this.length; i++) {
                if (this[i] === v) return true;
            }
            return false;
        };

        Array.prototype.distinct = function () {
            var arr = [];
            for (var i = 0; i < this.length; i++) {
                if (!arr.hasValue(this[i])) {
                    arr.push(this[i]);
                }
            }
            return arr;
        }

        var formValidations = {

            validateEmail: function (el) {
                if ($J(el).val().trim() != '') {
                    var mailformat = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{1,63}$/;
                    if ($(el).val().match(mailformat)) {
                        $(el).parent().find('.field-validation-valid').text('');
                        $(el).removeClass('invalid');
                    }
                    else {
                        var errorMessage = "Please enter valid email.";
                        $(el).parent().find('.field-validation-valid').text(errorMessage);

                        if (!$(el).hasClass('invalid')) {
                            $(el).addClass('invalid');
                        }
                    }
                }
            },
            validateText: function (el) {
                if ($J(el).val().trim() != '') {
                    var mailformat = /^[a-zA-Z ]+$/;
                    if ($(el).val().match(mailformat)) {
                        $(el).parent().find('.field-validation-valid').text('');
                        $(el).removeClass('invalid');
                    }
                    else {
                        var errorMessage = "Please use standard letters and spaces only.";
                        $(el).parent().find('.field-validation-valid').text(errorMessage);

                        if (!$(el).hasClass('invalid')) {
                            $(el).addClass('invalid');
                        }
                    }
                }
            },
            validatePhoneNumber: function (el) {
                if ($J(el).val().trim() != '') {
                    var mailformat = /\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/;
                    if ($(el).val().match(mailformat)) {
                        $(el).parent().find('.field-validation-valid').text('');
                        $(el).removeClass('invalid');
                    }
                    else {
                        var errorMessage = "Please enter valid phone number.";
                        $(el).parent().find('.field-validation-valid').text(errorMessage);

                        if (!$(el).hasClass('invalid')) {
                            $(el).addClass('invalid');
                        }
                    }
                }
            },
            validatePostalCode: function (el) {
                if ($J(el).val().trim() != '') {
                    var mailformat = /^[0-9]{4}$/;
                    if ($(el).val().match(mailformat)) {
                        $(el).parent().find('.field-validation-valid').text('');
                        $(el).removeClass('invalid');
                    }
                    else {
                        var errorMessage = "Please enter valid postcode.";
                        $(el).parent().find('.field-validation-valid').text(errorMessage);

                        if (!$(el).hasClass('invalid')) {
                            $(el).addClass('invalid');
                        }
                    }
                }
            },
            validateNumbersOnly: function (el) {
                if ($J(el).val().trim() != '') {
                    var mailformat = /^[0-9]+$/;
                    if ($(el).val().match(mailformat)) {
                        $(el).parent().find('.field-validation-valid').text('');
                        $(el).removeClass('invalid');
                    }
                    else {
                        var errorMessage = "Please use numerics only.";
                        $(el).parent().find('.field-validation-valid').text(errorMessage);

                        if (!$(el).hasClass('invalid')) {
                            $(el).addClass('invalid');
                        }
                    }
                }
            },
            validateAlphanumericOnly: function (el) {
                if ($J(el).val().trim() != '') {
                    var mailformat = /^[a-zA-Z0-9]*$/;
                    if ($(el).val().match(mailformat)) {
                        $(el).parent().find('.field-validation-valid').text('');
                        $(el).removeClass('invalid');
                    }
                    else {
                        var errorMessage = "Please use alphanumerics only.";
                        $(el).parent().find('.field-validation-valid').text(errorMessage);

                        if (!$(el).hasClass('invalid')) {
                            $(el).addClass('invalid');
                        }
                    }
                }
            },
            isInvalidDisplayName: function (el) {
                if ($J(el).val().trim() != '') {
                    var mailformat = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{1,63}$/;
                    if ($(el).val().match(mailformat)) {
                        return true;
                    }

                }
            },
        };

        $J(document).ready(function () {
            defaultFunctions.init();
        });
        /*masked Input type*/
        (function (a) { a.MaskedInput = function (f) { if (!f || !f.elm || !f.format) { return null } if (!(this instanceof a.MaskedInput)) { return new a.MaskedInput(f) } var o = this, d = f.elm, s = f.format, i = f.allowed || "0123456789", h = f.allowedfx || function () { return true }, p = f.separator || "/:-", n = f.typeon || "_YMDhms", c = f.onbadkey || function () { }, q = f.onfilled || function () { }, w = f.badkeywait || 0, A = f.hasOwnProperty("preserve") ? !!f.preserve : true, l = true, y = false, t = s, j = (function () { if (window.addEventListener) { return function (E, C, D, B) { E.addEventListener(C, D, (B === undefined) ? false : B) } } if (window.attachEvent) { return function (D, B, C) { D.attachEvent("on" + B, C) } } return function (D, B, C) { D["on" + B] = C } }()), u = function () { for (var B = d.value.length - 1; B >= 0; B--) { for (var D = 0, C = n.length; D < C; D++) { if (d.value[B] === n[D]) { return false } } } return true }, x = function (C) { try { C.focus(); if (C.selectionStart >= 0) { return C.selectionStart } if (document.selection) { var B = document.selection.createRange(); return -B.moveStart("character", -C.value.length) } return -1 } catch (D) { return -1 } }, b = function (C, E) { try { if (C.selectionStart) { C.focus(); C.setSelectionRange(E, E) } else { if (C.createTextRange) { var B = C.createTextRange(); B.move("character", E); B.select() } } } catch (D) { return false } return true }, m = function (D) { D = D || window.event; var C = "", E = D.which, B = D.type; if (E === undefined || E === null) { E = D.keyCode } if (E === undefined || E === null) { return "" } switch (E) { case 8: C = "bksp"; break; case 46: C = (B === "keydown") ? "del" : "."; break; case 16: C = "shift"; break; case 0: case 9: case 13: C = "etc"; break; case 37: case 38: case 39: case 40: C = (!D.shiftKey && (D.charCode !== 39 && D.charCode !== undefined)) ? "etc" : String.fromCharCode(E); break; default: C = String.fromCharCode(E); break } return C }, v = function (B, C) { if (B.preventDefault) { B.preventDefault() } B.returnValue = C || false }, k = function (B) { var D = x(d), F = d.value, E = "", C = true; switch (C) { case (i.indexOf(B) !== -1): D = D + 1; if (D > s.length) { return false } while (p.indexOf(F.charAt(D - 1)) !== -1 && D <= s.length) { D = D + 1 } if (!h(B, D)) { c(B); return false } E = F.substr(0, D - 1) + B + F.substr(D); if (i.indexOf(F.charAt(D)) === -1 && n.indexOf(F.charAt(D)) === -1) { D = D + 1 } break; case (B === "bksp"): D = D - 1; if (D < 0) { return false } while (i.indexOf(F.charAt(D)) === -1 && n.indexOf(F.charAt(D)) === -1 && D > 1) { D = D - 1 } E = F.substr(0, D) + s.substr(D, 1) + F.substr(D + 1); break; case (B === "del"): if (D >= F.length) { return false } while (p.indexOf(F.charAt(D)) !== -1 && F.charAt(D) !== "") { D = D + 1 } E = F.substr(0, D) + s.substr(D, 1) + F.substr(D + 1); D = D + 1; break; case (B === "etc"): return true; default: return false } d.value = ""; d.value = E; b(d, D); return false }, g = function (B) { if (i.indexOf(B) === -1 && B !== "bksp" && B !== "del" && B !== "etc") { var C = x(d); y = true; c(B); setTimeout(function () { y = false; b(d, C) }, w); return false } return true }, z = function (C) { if (!l) { return true } C = C || event; if (y) { v(C); return false } var B = m(C); if ((C.metaKey || C.ctrlKey) && (B === "X" || B === "V")) { v(C); return false } if (C.metaKey || C.ctrlKey) { return true } if (d.value === "") { d.value = s; b(d, 0) } if (B === "bksp" || B === "del") { k(B); v(C); return false } return true }, e = function (C) { if (!l) { return true } C = C || event; if (y) { v(C); return false } var B = m(C); if (B === "etc" || C.metaKey || C.ctrlKey || C.altKey) { return true } if (B !== "bksp" && B !== "del" && B !== "shift") { if (!g(B)) { v(C); return false } if (k(B)) { if (u()) { q() } v(C, true); return true } if (u()) { q() } v(C); return false } return false }, r = function () { if (!d.tagName || (d.tagName.toUpperCase() !== "INPUT" && d.tagName.toUpperCase() !== "TEXTAREA")) { return null } if (!A || d.value === "") { d.value = s } j(d, "keydown", function (B) { z(B) }); j(d, "keypress", function (B) { e(B) }); j(d, "focus", function () { t = d.value }); j(d, "blur", function () { if (d.value !== t && d.onchange) { d.onchange() } }); return o }; o.resetField = function () { d.value = s }; o.setAllowed = function (B) { i = B; o.resetField() }; o.setFormat = function (B) { s = B; o.resetField() }; o.setSeparator = function (B) { p = B; o.resetField() }; o.setTypeon = function (B) { n = B; o.resetField() }; o.setEnabled = function (B) { l = B }; return r() } }(window));

        function GetWishListType(type) {
            var wishlisttype = 'article';
            if (type != undefined && type != '') {
                switch (type) {
                    case "Tutorials": wishlisttype = 'Tutorial';
                        break;
                    default:
                        wishlisttype = type;
                        break;
                }
            }
            return wishlisttype;
        }

    });
}(jQuery, window, document));;
var canonHelper = (function () {
    var _helperScope = {

        isSpinnerVisible: false,

        getQueryString: function (parameters) {
            var pageUrl = window.location.search.substring(1);
            if (pageUrl.length === 0) {
                return "";
            }
            var urlVariables = pageUrl.split("&");
            for (var i = 0; i < urlVariables.length; i++) {
                var sParameterName = urlVariables[i].split("=");
                if (sParameterName[0] === parameters) {
                    return sParameterName[1];
                }
            }
            return "";
        },

        isMobile: function () {
            return /Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion);
        },

        addAntiForgeryToken: function (data) {
            data.__RequestVerificationToken = $('input[name="__RequestVerificationToken"]').val();
            return data;
        },

        showSpinner: function () {
            if (!_helperScope.isSpinnerVisible) {
                $("div#spinner").fadeIn("fast");
                $(".image-spinner").html("Loading");
                _helperScope.isSpinnerVisible = true;
            }
        },

        hideSpinner: function () {
            if (_helperScope.isSpinnerVisible) {
                var spinner = $("div#spinner");
                spinner.stop();
                spinner.fadeOut("fast");
                _helperScope.isSpinnerVisible = false;
            }
        },

        setCookie: function (cname, cvalue, exdays) {
            var d = new Date();
            d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
            var expires = "expires=" + d.toUTCString();
            document.cookie = cname + "=" + cvalue + "; " + expires;
        },

        getCookie: function (cname) {
            var name = cname + "=";
            var ca = document.cookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) == ' ') c = c.substring(1);
                if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
            }
            return "";
        },

        getScript: function (url, options) {
            options = $.extend(options || {}, { dataType: "script", cache: true, url: url });
            return jQuery.ajax(options);
        },

        tileMarginFix: function (ulElement) {
            if (ulElement && ulElement.length > 0) {
                $ul = $(ulElement);
                $top = -1;
                $row = 0;

                $ul.find('li').each(function (a, b) {
                    $li = $(this);

                    if ($li.position().top > $top) {
                        $row++;
                        $top = $li.position().top;
                        $li.addClass("margin--l0");
                    } else {
                        $li.removeClass("margin--l0");
                    }

                    if (parseFloat($(this).css("margin-bottom")) == 0) {
                        $(this).css("margin-bottom", parseFloat($(this).parent().css("width")) * 0.0125);
                    }
                });
            }
            else {
                $('div[class*="tiled--"] ul').each(function (a, b) {
                    $ul = $(this);
                    $top = -1;
                    $row = 0;

                    $ul.find('li').each(function (a, b) {
                        $li = $(this);

                        if ($li.position().top > $top) {
                            $row++;
                            $top = $li.position().top;
                            $li.addClass("margin--l0");
                        } else {
                            $li.removeClass("margin--l0");
                        }
                    });
                });
                /* overcome ff issue with zero bottom margin. known bug firefox */
                $('div[class*="tiled--"] ul li').each(function (a, b) {
                    if (parseFloat($(this).css("margin-bottom")) == 0) {
                        $(this).css("margin-bottom", parseFloat($(this).parent().css("width")) * 0.0125);
                    }
                });
            }
        },

        constructVideoElement: function () {

            function makeModal(v, w, h) {
                var frame = '<div class="hero-modal" aria-hidden="true"><button><span class="icomoon-Close"></span></button><div class="flexbox--center"><iframe width="' + w + '" height="' + h + '" src="' + v + '?autoplay=1" frameborder="0" allowfullscreen></iframe></div></div>';
                $('body').prepend(frame);
                TweenMax.fromTo($('.hero-modal'), 0.35, { css: { scale: 0 } }, { css: { scale: 1 } });
                $(document).keyup(function (e) {
                    if (e.keyCode == 27) {
                        destroyModal();
                    }
                });
                $('.hero-modal button').on('click', destroyModal);
            }

            function destroyModal() {
                TweenMax.fromTo($('.hero-modal'), 0.35, { css: { scale: 1 } }, {
                    css: { scale: 0, opacity: 0 }, onComplete: function () {
                        $('.hero-modal button').unbind('click');
                        $('.hero-modal').remove();
                        $(document).unbind('keyup');

                    }
                });
            }

            $("iframe[src*='youtube.com'], iframe[src*='vimeo.com']").each(function (index) {
                $(this).attr('data-src', $(this).attr('src'));
                $(this).attr('data-aspect', $(this).attr('width') / $(this).attr('height'));
                $(this).attr('src', '');
                if ($(this).parent().prop('nodeName') === "FIGURE") {
                    $parent = $(this).parent();
                    $parent.addClass("video");
                    $parent.prepend('<div class="vid-img-placeholder"><div class="icon-svg-playbutton"></div></div>');
                    $parent.find('img').appendTo('.vid-img-placeholder', $parent);

                }

            });

            $('figure.video').on('click', function () {
                $el = $(this).find('iframe');
                makeModal($el.attr('data-src'), $el.attr('width'), $el.attr('height'));
            });


            $('.play.video').each(function () {
                $parent = $(this).parent();
                $target = $(this);
                //prevent the parent link from firing
                if ($parent.is('a')) {
                    $parent.on('click', function (event) {
                        event.preventDefault();
                        $target.trigger('click');
                    });
                }
            });

            $('.play.video, li[class*="tile--1"] .video').on('click', function () {
                $el = $(this).find('iframe');
                makeModal($el.attr('data-src'), $el.attr('width'), $el.attr('height'));
            });
        },

        initImageLazyLoad: function(){
            // window.addEventListener("load", function(event) {
            //     $("img.lazyload").lazyload();
            // });

            window.lazySizesConfig = window.lazySizesConfig || {};
            lazySizesConfig.expand = 10;
        }
    };

    return _helperScope;
})();;
(function ($J) {
    var explore = (function () {
        var _exploreScope = {
            init: function () {
                this.initEventMap();
                this.initExploreFilterByPillar();
                this.initExploreEventListingFeedFilter();
                this.initExploreFilterByKeyword();
                this.initExploreListingFeedLoadMore();
                this.initEventContentFeed();
                this.browseHash();
            },

            changeHashelement: function (hash) {

                if (!hash || hash == '') return null;

                var id = "#" + hash;
                var tempElement = $J(id);
                if (tempElement) {
                    tempElement.attr('data-filtertype', '');
                    var filterType = tempElement.attr("data-filter-type");
                    var filterKey = tempElement.attr("data-filter-key");
                    var filterText = tempElement.text();

                    if (filterKey == undefined) {
                        filterKey = '';
                    }

                    tempElement.closest('.filter-options-container').toggleClass('active');
                    tempElement.closest('.filter-options-container').attr('data-filtertype', '');
                    tempElement.closest('.filter-options-container').parent().find('button*[data-filter-type="' + filterType + '"]').attr('data-selectedkey', filterKey);
                    tempElement.closest('.filter-options-container').parent().find('button*[data-filter-type="' + filterType + '"]').text(filterText);

                    tempElement.closest('ul').find('.select-option.under').each(function () {
                        $J(this).removeClass('under');
                    });

                    if (!tempElement.hasClass("under")) {
                        tempElement.addClass("under");


                        return tempElement;
                    }
                }
                return null;
            },

            browseHash: function () {

                var hash = window.location.hash.substr(1);

                var result = hash.split('&').reduce(function (result, item) {
                    var parts = item.split('=');
                    result[parts[0]] = parts[1];
                    return result;
                }, {});

                var locationHash = result["location"];
                var timeHash = result["time"];
                var searchHash = result["search"];

                if (searchHash) {
                    locationHash = locationHash ? locationHash : "AnyLocation";
                    timeHash = timeHash ? timeHash : "AnyTime";
                    searchHash = decodeURI(result["search"].toString());
                }


                var locationElement = _exploreScope.changeHashelement(locationHash);
                var timeElement = _exploreScope.changeHashelement(timeHash);

                var tempElement = locationElement ? locationElement : timeElement ? timeElement : null;

                if (tempElement) {
                    _exploreScope.exploreFilterOptionsHandler(tempElement, searchHash);
                }

            },

            exploreFilterOptionsHandler: function (actionTriggered, keyWord) { /*  for filter */
                var locationFilterKey = "";
                var timeLineFilterKey = "";
                var skillLevelFilterKey = "";
                var priceFilterKey = "";
                var sourceId = "";
                var groupsizeFilterKey = "";
                var photographyStyleFilterKey = "";
                var durationFilterKey = "";
                var currentPageId = "";
                var tileContainer = {};
                var selectFromFilterOption = actionTriggered.hasClass("select-option") || actionTriggered.hasClass("update-all-btn");
                var selectedPillar = '';
                var filterKey = '';
                var filterType = '';
                var pageToRender = 0;
                var keyword = '';
                var selectedEventIds = null;

                var eventsFilterContainer = {};

                var mobileContainer = $J(actionTriggered).closest('.mobile');
                var isMobile = mobileContainer != null && mobileContainer !== undefined && mobileContainer.length > 0;
                var isEventFeed = false;

                actionTriggered.closest(".nv15").find(".explore-feed-keyword").val('');

                if (selectFromFilterOption) {
                    sourceId = actionTriggered.closest(".events-filter-container").siblings('.explore-content-feed').attr('data-source');
                    currentPageId = actionTriggered.closest(".events-filter-container").siblings('.explore-content-feed').attr('data-currentpage');
                    tileContainer = actionTriggered.closest(".events-filter-container").siblings('.explore-content-feed').find(".tile-container");
                    eventsFilterContainer = actionTriggered.closest(".events-filter-container");
                } else {
                    sourceId = actionTriggered.closest(".explore-content-feed").attr('data-source');
                    currentPageId = actionTriggered.closest(".explore-content-feed").attr('data-currentpage');
                    var exploreContentFeedContainer = actionTriggered.closest('.explore-content-feed');
                    tileContainer = exploreContentFeedContainer.find(".tile-container");
                    var currentPageIndex = $J(actionTriggered).attr("data-current-page");
                    pageToRender = parseInt(currentPageIndex) + 1;
                    eventsFilterContainer = exploreContentFeedContainer.siblings(".events-filter-container");

                    var pillarFilterContainer = exploreContentFeedContainer.parent().find('.pillar-filter-container');
                    if (pillarFilterContainer && pillarFilterContainer.length > 0 && pillarFilterContainer.find('.explore-filter-key.under').length > 0) {
                        var pillarElement = pillarFilterContainer.find('.explore-filter-key.under')[0];
                        var selectedOption = $(pillarElement).attr('data-filter-key');
                        pillarFilterContainer.attr('data-selected-filter', selectedOption);
                        selectedPillar = selectedOption;
                    }
                }

                if (eventsFilterContainer && eventsFilterContainer.length > 0) {
                    isEventFeed = true;
                    $J(eventsFilterContainer).find('.select-option.under').each(function () {
                        var currentMobileContainer = $J(this).closest('.mobile');

                        if (isMobile && currentMobileContainer != null && currentMobileContainer.length > 0) {
                            setFilterKey($J(this));
                        }
                        else if (!isMobile && (currentMobileContainer != undefined && currentMobileContainer.length === 0)) {
                            setFilterKey($J(this));
                        }

                        function setFilterKey(el) {
                            filterKey = $J(el).attr('data-filter-key');
                            filterType = $J(el).attr('data-filter-type');

                            if (filterType === "Location") {
                                locationFilterKey = filterKey;
                            }
                            if (filterType === "Timeline") {
                                timeLineFilterKey = filterKey;
                            }
                        }
                    });

                    $J(eventsFilterContainer).find('.select-other-option.under').each(function () {
                        var currentMobileContainer = $J(this).closest('.mobile');

                        if (isMobile && currentMobileContainer != null && currentMobileContainer.length > 0) {
                            setFilterKey($J(this));
                        }
                        else if (!isMobile && (currentMobileContainer != undefined && currentMobileContainer.length === 0)) {
                            setFilterKey($J(this));
                        }

                        function setFilterKey(el) {
                            var filterKey = $J(el).attr('data-filter-key');
                            var filterType = $J(el).attr('data-filter-type');
                            if (filterType === "SkillLevel") {
                                skillLevelFilterKey = filterKey;
                            }
                            if (filterType === "Prices") {
                                priceFilterKey = filterKey;
                            }
                        }
                    });

                    // Apply search key word
                    keyword = keyWord ? keyWord : '';
                    if ($J(eventsFilterContainer).find('.explore-feed-keyword').length > 0) {
                        $J(eventsFilterContainer).find('.explore-feed-keyword').val(keyword);
                        $J(eventsFilterContainer).find('.explore-feed-keyword').attr('data-keyword', keyword);
                    }
                }

                selectedEventIds = $J("#selected-event-ids").val().toString();

                var postData = {
                    CurrentExploreCategoryPageId: sourceId,
                    CurrentFarmFeedDataSourceId: sourceId,
                    CurrentPageId: currentPageId,
                    PageIndex: pageToRender,
                    PageSize: 0,
                    ApplyFilter: true,
                    SelectedPillar: selectedPillar,
                    SelectedLocation: locationFilterKey,
                    SelectedTimeline: timeLineFilterKey,
                    SelectedSkillLevel: skillLevelFilterKey,
                    SelectedPriceRange: priceFilterKey,
                    SelectedGroupSize: groupsizeFilterKey,
                    SelectedPhotographyStyle: photographyStyleFilterKey,
                    SelectedDuration: durationFilterKey,
                    Keyword: keyword,
                    IsEventFeed: isEventFeed,
                    SelectedEventIds: selectedEventIds
                };

                _exploreScope.getExploreFeed(postData, tileContainer, selectFromFilterOption);

                if (isMobile && selectFromFilterOption) {
                    $J(mobileContainer).find('.close').trigger('click');
                }
            },

            resetEventFilterToDefault: function (isReloadData, excludeSearchBar) {
                if ($J('.events-filter-container').length > 0) {
                    var eventFilterContainer = $J('.events-filter-container');
                    var filterOptionsContainer = $J('.filter-options-container');

                    eventFilterContainer.find('a.under').removeClass('under');
                    eventFilterContainer.find('.events-filter-select').removeAttr('data-selectedkey');

                    var defaultTimelineFilterOption = filterOptionsContainer.find('a[data-filter-type="Timeline"]:first');
                    var defaultTimelineFilterKey = $J(defaultTimelineFilterOption).attr('data-filter-key');
                    var timelineFilterButton = eventFilterContainer.find('.events-filter-select[data-filter-type="Timeline"]');
                    timelineFilterButton.attr('data-selectedkey', defaultTimelineFilterKey);
                    timelineFilterButton.text($J(defaultTimelineFilterOption).text());
                    defaultTimelineFilterOption.addClass('under');

                    var defaultLocationFilterOption = filterOptionsContainer.find('a[data-filter-type="Location"]:first');
                    var defaultLocationFilterKey = $J(defaultLocationFilterOption).attr('data-filter-key');
                    var locationFilterButton = eventFilterContainer.find('.events-filter-select[data-filter-type="Location"]');
                    locationFilterButton.attr('data-selectedkey', defaultLocationFilterKey);
                    locationFilterButton.text($J(defaultLocationFilterOption).text());
                    defaultLocationFilterOption.addClass('under');

                    if (!excludeSearchBar) {
                        var eventsSearch = $J(eventFilterContainer).find('.explore-feed-keyword');
                        $J(eventsSearch).val('');
                        $J(eventsSearch).attr('data-keyword', '');
                    }

                    if (isReloadData) {
                        var sourceId = eventFilterContainer.siblings('.explore-content-feed').attr('data-source');
                        var currentPageId = eventFilterContainer.siblings('.explore-content-feed').attr('data-currentpage');
                        var tileContainer = eventFilterContainer.siblings('.explore-content-feed').find(".tile-container");

                        var postData = {
                            CurrentExploreCategoryPageId: sourceId,
                            CurrentFarmFeedDataSourceId: sourceId,
                            CurrentPageId: currentPageId,
                            PageIndex: 0,
                            PageSize: 0,
                            ApplyFilter: true,
                            SelectedPillar: '',
                            SelectedLocation: defaultLocationFilterKey,
                            SelectedTimeline: defaultTimelineFilterKey,
                            SelectedSkillLevel: '',
                            SelectedPriceRange: '',
                            Keyword: '',
                            IsEventFeed: true
                        };

                        _exploreScope.getExploreFeed(postData, tileContainer, true);
                        $J(filterOptionsContainer).slideUp(500);

                    }
                }
            },

            resetStoriesFilterToDefault: function (isReloadData, excludeSearchBar) {
                if ($J('.filter-container').length > 0) {
                    var filterContainer = $J('.filter-container');
                    var filterOptionsContainer = filterContainer.find('.pillar-filter-container');

                    filterContainer.find('a.under').removeClass('under');
                    filterOptionsContainer.removeAttr('data-selected-filter');

                    var defaultFilterOption = filterOptionsContainer.find('a:first');
                    var filterButton = filterContainer.find('.filter-a');
                    filterButton.text($J(defaultFilterOption).text());
                    defaultFilterOption.addClass('under');

                    if (!excludeSearchBar) {
                        var eventsSearch = $J(filterContainer).find('.explore-feed-keyword');
                        $J(eventsSearch).val('');
                        $J(eventsSearch).attr('data-keyword', '');
                    }

                    if (isReloadData) {
                        var sourceId = filterContainer.siblings('.explore-content-feed').attr('data-source');
                        var tileContainer = filterContainer.siblings('.explore-content-feed').find(".tile-container");

                        var postData = {
                            CurrentExploreCategoryPageId: sourceId,
                            CurrentFarmFeedDataSourceId: sourceId,
                            CurrentPageId: 0,
                            PageIndex: 0,
                            PageSize: 0,
                            ApplyFilter: true,
                            SelectedPillar: '',
                            SelectedLocation: '',
                            SelectedTimeline: '',
                            SelectedSkillLevel: '',
                            SelectedPriceRange: '',
                            Keyword: ''
                        };

                        _exploreScope.getExploreFeed(postData, tileContainer, true);
                        $J(filterOptionsContainer).slideUp(500);

                    }
                }
            },

            initEventMap: function () {
                if ($J('.event-map').length > 0) {
                    $J('.event-map').each(function () {
                        var latitude = parseFloat($J(this).attr("data-latitude"));
                        var longitude = parseFloat($J(this).attr("data-longitude"));
                        var containerId = $J(this).attr("data-container");
                        if (latitude && longitude && containerId) {
                            var location = $J(this).attr("data-location");
                            var latlng = { lat: latitude, lng: longitude };

                            var map = new google.maps.Map($J(this)[0], {
                                center: latlng,
                                zoom: 15
                            });
                            var marker = new google.maps.Marker({
                                position: latlng,
                                map: map,
                                title: location
                            });
                            google.maps.event.addDomListener(window, 'resize', function () {
                                var center = map.getCenter();
                                google.maps.event.trigger(map, "resize");
                                map.setCenter(center);
                            });
                        }
                    });
                }
            },

            getExploreFeed: function (postData, tileContainer, replaceHtml) {
                canonHelper.showSpinner();

                var hash = postData.SelectedLocation ? 'location=' + postData.SelectedLocation + '&' : '';
                hash += postData.SelectedTimeline ? 'time=' + postData.SelectedTimeline + '&' : '';
                hash += postData.Keyword ? 'search=' + postData.Keyword : '';

                if (hash && hash != '') {
                    window.location.hash = hash;
                }
                var useforfeed = $J("#useforfarmfeed").val();
                var url = $J("#explore-feed-url").val();

                if (url == undefined || url === '') {
                    url = '/content-tile/explore/getexplorelistingfeed';
                }

                if (useforfeed != undefined && useforfeed) {
                    url = '/content-tile/thefarm/geteventcontentfeedfarm';
                }
                var data = canonHelper.addAntiForgeryToken(postData);
                var post = $J.post(url, data);

                post.done(function (data) {
                    var template;
                    // Try loading the external template files
                    var templateType = $J('#explore-feed-template').val();
                    if (templateType == undefined || templateType === '') {
                        templateType = 'content-listing-feed';
                    }

                    $.when($.get("/mustachetemplates/" + templateType + ".html", function (source) { template = source; }))
                        .then(function () {
                            var noDataFoundEl = $J(tileContainer).parent().find(".explore-feed-empty");
                            var loadMoreEl = $J(tileContainer).parent().find(".explore-load-more-feed a");
                            var loadMoreContainerEl = $J(tileContainer).parent().find(".explore-load-more-feed");

                            if ((data.ContentListingFeedSkinnyTiles && data.ContentListingFeedSkinnyTiles.length > 0) || 
                                (data.Items && data.Items.length > 0)) {
                                var result = Mustache.to_html(template, data);
                                noDataFoundEl.slideUp(500);

                                if (replaceHtml) {
                                    $J(tileContainer).html(result);
                                } else {
                                    $J(tileContainer).append(result);
                                }

                                $J(tileContainer).slideDown(500);
                                canonHelper.constructVideoElement();
                                canonHelper.tileMarginFix($J(tileContainer));

                            }
                            else {
                                if (noDataFoundEl.hasClass("hide--me")) {
                                    noDataFoundEl.removeClass("hide--me");
                                }

                                $J(tileContainer).slideUp(500);
                                noDataFoundEl.slideDown(500);
                            }

                            var nextDataToDisplay = parseInt(data.NextItemToDisplayed);
                            var maxDataToDisplay = parseInt(data.TotalPagesFound);
                            var pageSize = parseInt(data.PageSize);

                            if (data && nextDataToDisplay > 0) {
                                $J(loadMoreEl).attr('data-page-size', pageSize);
                                $J(loadMoreEl).attr('data-hit-counter', 0);
                                $J(loadMoreEl).attr('data-slice-max', data.TotalPagesFound);
                                $J(loadMoreEl).attr('data-slice-next', nextDataToDisplay);
                                $J(loadMoreEl).attr('data-slice-start', pageSize);
                                $J(loadMoreEl).attr('data-slice-end', pageSize * 2 <= maxDataToDisplay ? pageSize * 2 : maxDataToDisplay);

                                var tilesTypeForLoadMore = $J(loadMoreEl).attr('data-tiles-type');
                                var tilesTypeForLoadMoreText = $J(loadMoreEl).attr('data-tiles-counter-text');
                                var tilesCounterForLoadMore = nextDataToDisplay > 1 ? tilesTypeForLoadMoreText + 's' : tilesTypeForLoadMoreText;

                                var loadMoreText = "<span>Load more " + tilesTypeForLoadMore + "</span><br>" + "(" + nextDataToDisplay + ") " + tilesCounterForLoadMore + " left";
                                $J(loadMoreEl).html(loadMoreText);

                                $J(loadMoreContainerEl).removeClass('hide--me');
                            } else {
                                if (!loadMoreContainerEl.hasClass('hide--me')) {
                                    loadMoreContainerEl.addClass('hide--me');
                                }
                            }

                            canonHelper.hideSpinner();

                        },
                        function () {
                            // templates not loaded
                            var templateError = 'Error: Could not load plugin templates. Check the paths and ensure they have been uploaded. Paths will be wrong if you do not run this from a web server.'; console.log(templateError);
                            canonHelper.hideSpinner();
                        });
                });

                post.fail(function () {
                    canonHelper.hideSpinner();
                });

                post.always(function () {

                });
            },

            initExploreFilterByPillar: function () {
                if ($J('.explore-content-feed').length > 0) {
                    $J('.filter-container .filter-a').on('click', function () {
                        var filterContainer = $J(this).attr('data-filter-content-id');
                        $J(this).closest('.nv15').find("." + filterContainer).toggleClass('active');
                    });

                    //desktop
                    $J('.explore-filter-key').on('click', function (el) {
                        el.preventDefault();

                        var currentElement = $J(this);

                        var filterKey = $J(currentElement).attr('data-filter-key');
                        var pillarFilterContainer = $J(currentElement).closest('.pillar-filter-container');
                        pillarFilterContainer.attr('data-selected-filter', filterKey);
                        var filterContainer = $J(currentElement).closest('.filter-container');

                        var sourceId = filterContainer.siblings('.explore-content-feed').attr('data-source');
                        var currentPageId = filterContainer.siblings('.explore-content-feed').attr('data-currentpage');
                        var tileContainer = filterContainer.siblings('.explore-content-feed').find(".tile-container");

                        if ($J(filterContainer).find('.explore-feed-keyword').length > 0) {
                            $J(filterContainer).find('.explore-feed-keyword').val('');
                            $J(filterContainer).find('.explore-feed-keyword').removeAttr('data-keyword');
                        }

                        pillarFilterContainer.find('a.under').removeClass('under');
                        pillarFilterContainer.siblings('.selectors').find('.filter-a').text($J(currentElement).text());

                        if (!$J(currentElement).hasClass('under')) {
                            $J(currentElement).addClass('under');
                        }

                        $J(currentElement).closest('.nv15.filter-container').find('.mobile option').each(function () {
                            $J(this).removeAttr('selected');

                            if ($J(this).attr('data-filter-key') === filterKey) {
                                $J(this).attr('selected', '');
                                $J(this).parent('select').val(filterKey);
                            }
                        });

                        var postData = {
                            CurrentExploreCategoryPageId: sourceId,
                            CurrentFarmFeedDataSourceId: sourceId,
                            CurrentPageId: currentPageId,
                            PageIndex: 0,
                            PageSize: 0,
                            ApplyFilter: true,
                            SelectedPillar: filterKey,
                            SelectedLocation: "",
                            SelectedSkillLevel: "",
                            SelectedPriceRange: "",
                            Keyword: ''
                        };

                        _exploreScope.getExploreFeed(postData, tileContainer, true);

                        pillarFilterContainer.toggleClass('active');

                    });

                    //mobile
                    $J(".explore-listing-feed-filter").on("change", function (e) {
                        var selectedFilter = $J(this).find(':selected').attr('data-filter-key');

                        if ($J(this).closest('.mobile').css('display') !== 'none') {
                            $J(this).closest('.nv15.filter-container').find('li').each(function () {
                                if ($J(this).attr('data-filter') === selectedFilter) {
                                    $J(this).trigger('click');
                                }
                            });
                        }

                    });
                }
            },

            initExploreEventListingFeedFilter: function () {
                $(document).off('click', '.events-filter-select');
                $(document).on('click', '.events-filter-select', function (e) {
                    e.preventDefault();
                    e.stopPropagation();

                    var currentElement = $J(this);

                    var activeFilterOptions = $J(currentElement).attr('data-options-placeholder');
                    var activeFilterKey = $J(currentElement).attr('data-selectedkey');
                    var exploreFeedContainer = $J(currentElement).closest('.events-filter-container').siblings('.explore-content-feed');
                    var filterOptionsContainerEl = $J(currentElement).closest('.events-filter-container').find('.filter-options-container');
                    var currentExploreFilterType = $J(filterOptionsContainerEl).attr('data-filtertype');

                    var mobileContainer = $J(currentElement).closest('.mobile');
                    var isMobile = mobileContainer != null && mobileContainer != undefined && mobileContainer.length > 0;
                    if (!isMobile) {
                        $J(currentElement).attr('disabled', 'disabled');

                        if ($J(filterOptionsContainerEl).hasClass('active')) {
                            $J(filterOptionsContainerEl).removeClass('active');
                        }

                        if (activeFilterOptions === currentExploreFilterType) {
                            $J(filterOptionsContainerEl).removeClass('active');
                            $J(filterOptionsContainerEl).attr('data-filtertype', '');
                            if (exploreFeedContainer.length > 0 && $J(exploreFeedContainer).hasClass('filter-active')) {
                                $J(exploreFeedContainer).removeClass('filter-active');
                            }

                            $J(filterOptionsContainerEl).slideUp(500, function () {
                                $J(currentElement).removeAttr('disabled');
                            });

                        } else {
                            $J(filterOptionsContainerEl).attr('data-filtertype', activeFilterOptions);

                            if (filterOptionsContainerEl.length > 0) {
                                $J(filterOptionsContainerEl).find('.filter-type').each(function () {
                                    $J(this).hide();
                                });
                                var filtersContainerEl = $J(filterOptionsContainerEl).find('.' + activeFilterOptions);
                                if (filtersContainerEl.length > 0) {

                                    if (activeFilterOptions === "other-options") {
                                        if (activeFilterKey) {
                                            var keys = activeFilterKey.split(',');
                                            $J(filtersContainerEl).find('.select-other-option.under').each(function () {
                                                $J(this).removeClass('under');
                                            });
                                            jQuery.each(keys, function (i, val) {
                                                $J(filtersContainerEl).find('.select-other-option*[data-filter-key="' + val + '"]').addClass('under');
                                            });
                                        }
                                        if (exploreFeedContainer.length > 0 && !$J(exploreFeedContainer).hasClass('filter-active')) {
                                            $J(exploreFeedContainer).addClass('filter-active');
                                        }
                                    }
                                    else {
                                        $J(filtersContainerEl).find('.select-option*[data-filter-key="' + activeFilterKey + '"]').addClass('under');
                                    }

                                    filtersContainerEl.show();
                                    $J(filterOptionsContainerEl).addClass('active');
                                    $J(filterOptionsContainerEl).slideDown(500, function () {
                                        $J(currentElement).removeAttr('disabled');
                                    });
                                }
                            }
                        }
                    }
                    else {
                        $J(mobileContainer).find('.events-filter-select.m-active').not(currentElement).each(function () {
                            $J(this).removeClass('m-active');
                        });

                        if ($J(currentElement).hasClass('m-active')) {
                            $J(currentElement).removeClass('m-active');
                        }
                        else {
                            $J(currentElement).addClass('m-active');
                        }
                    }
                });

                $J(".select-other-option").off('click');
                $J(".select-other-option").on("click", function (e) {
                    e.preventDefault();
                    e.stopPropagation();

                    var $this = $J(this);
                    var listContainer = $this.closest('ul');

                    listContainer.find('.select-other-option').each(function () {
                        if ($J(this).hasClass('under')) {
                            $J(this).removeClass('under');
                        }
                    });

                    $this.addClass("under");
                });

                $J('.select-option').off('click');
                $J('.select-option').on('click', function (e) {
                    e.preventDefault();
                    e.stopPropagation();
                    $J(this).closest('.filter-options-container').attr('data-filtertype', '');

                    var filterType = $J(this).attr("data-filter-type");
                    var filterKey = $J(this).attr("data-filter-key");
                    var filterText = $J(this).text();

                    if (filterKey == undefined) {
                        filterKey = '';
                    }

                    $J(this).closest('.filter-options-container').toggleClass('active');
                    $J(this).closest('.filter-options-container').attr('data-filtertype', '');
                    $J(this).closest('.filter-options-container').parent().find('button*[data-filter-type="' + filterType + '"]').attr('data-selectedkey', filterKey);
                    $J(this).closest('.filter-options-container').parent().find('button*[data-filter-type="' + filterType + '"]').text(filterText);

                    $J(this).closest('ul').find('.select-option.under').each(function () {
                        $J(this).removeClass('under');
                    });

                    if (!$J(this).hasClass("under")) {
                        $J(this).addClass("under");
                        _exploreScope.exploreFilterOptionsHandler($J(this));
                    }

                });

                $J('.update-all-btn').off('click');
                $J('.update-all-btn').on('click', function (el) {
                    el.preventDefault();
                    var $this = $J(this);

                    var mobileContainer = $J($this).closest('.mobile');
                    var isMobile = mobileContainer != null && mobileContainer != undefined && mobileContainer.length > 0;

                    var filterContainer = $J(this).closest('.filter-options-container');
                    var exploreFeedContainer = $J(filterContainer).parent().siblings('.explore-content-feed');
                    var filterType = $J(filterContainer).attr("data-filtertype");
                    var filterActionDropdown = {};

                    if (isMobile) {
                        filterActionDropdown = $J(mobileContainer).find('.m-active');

                        $(filterActionDropdown).attr('data-selectedkey', '');
                        $J(mobileContainer).attr('data-filtertype', '');

                        $J(mobileContainer).find('.select-other-option.under').each(function () {
                            var filterKey = $J(this).attr("data-filter-key");
                            var currentKeys = $(filterActionDropdown).attr('data-selectedkey');
                            if (currentKeys) {
                                $(filterActionDropdown).attr('data-selectedkey', currentKeys + ',' + filterKey);
                            }
                            else {
                                $(filterActionDropdown).attr('data-selectedkey', filterKey);
                            }

                        });
                    }
                    else {
                        filterActionDropdown = $J(filterContainer).parent().find('button*[data-options-placeholder="' + filterType + '"]');

                        $(filterActionDropdown).attr('data-selectedkey', '');
                        $J(filterContainer).attr('data-filtertype', '');

                        $J(filterContainer).find('.select-other-option.under').each(function () {
                            var filterKey = $J(this).attr("data-filter-key");
                            var currentKeys = $(filterActionDropdown).attr('data-selectedkey');
                            if (currentKeys) {
                                $(filterActionDropdown).attr('data-selectedkey', currentKeys + ',' + filterKey);
                            }
                            else {
                                $(filterActionDropdown).attr('data-selectedkey', filterKey);
                            }

                        });

                        $J(filterContainer).slideUp(500);


                        if (exploreFeedContainer.length > 0) {
                            $J(exploreFeedContainer).removeClass('filter-active');
                        }
                    }

                    _exploreScope.exploreFilterOptionsHandler($this);
                });

                $J('.clear-all-btn').off('click');
                $J('.clear-all-btn').on('click', function (el) {
                    el.preventDefault();

                    var mobileContainer = $J($this).closest('.mobile');
                    var isMobile = mobileContainer != null && mobileContainer != undefined && mobileContainer.length > 0;

                    _exploreScope.resetEventFilterToDefault(true, false);

                    if (isMobile) {
                        $J(mobileContainer).find('.close').trigger('click');
                    }
                });
            },

            initExploreFilterByKeyword: function () {
                $J('.explore-feed-keyword').keypress(function (e) {
                    if (e.which === 13) {
                        var keyword = $J(this).val();
                        var currentKeyword = $J(this).attr('data-keyword');
                        if (currentKeyword == undefined || currentKeyword !== keyword) {
                            searchByKeyword(keyword, $J(this));
                            $J(this).attr('data-keyword', keyword);
                        }
                    }
                });

                $J('.explore-feed-keyword-btn').on('click', function () {
                    var keyword = $J(this).parent().find(".explore-feed-keyword").val();
                    var currentKeyword = $J(this).parent().find(".explore-feed-keyword").attr('data-keyword');
                    if (currentKeyword == undefined || currentKeyword !== keyword) {
                        $J(this).parent().find(".explore-feed-keyword").attr('data-keyword', keyword);
                        searchByKeyword(keyword, $J(this));
                    }
                });

                function searchByKeyword(keyword, el) {
                    var locationFilterKey = "";
                    var timeLineFilterKey = "";
                    var skillLevelFilterKey = "";
                    var priceFilterKey = "";
                    var filterType = '';

                    var filterContainer = $J(el).closest('.filter-container');

                    var isEventFeed = filterContainer.length === 0;
                    if (isEventFeed) {
                        filterContainer = $J(el).closest('.events-filter-container');
                        _exploreScope.resetEventFilterToDefault(false, true);
                    }
                    else {
                        _exploreScope.resetStoriesFilterToDefault(false, true);
                        filterContainer.find('.pillar-filter-container').removeClass('active');
                    }

                    var sourceId = filterContainer.siblings(".explore-content-feed").attr('data-source');
                    var currentPageId = filterContainer.siblings(".explore-content-feed").attr('data-currentpage');
                    var tileContainer = filterContainer.siblings(".explore-content-feed").find(".tile-container");

                    var filterKey = '';
                    var selectedPillar = $J(el).closest('.filter-container').find('.pillar-filter-container').attr('data-selected-filter');
                    if (selectedPillar == undefined) {
                        selectedPillar = '';
                    }

                    $J(filterContainer).find('.select-option.under').each(function () {
                        filterKey = $J(this).attr('data-filter-key');
                        filterType = $J(this).attr('data-filter-type');

                        if (filterType === "Location") {
                            locationFilterKey = filterKey;
                        }
                        if (filterType === "Timeline") {
                            timeLineFilterKey = filterKey;
                        }
                    });

                    $J(filterContainer).find('.select-other-option.under').each(function () {
                        var filterKey = $J(this).attr('data-filter-key');
                        var filterType = $J(this).attr('data-filter-type');
                        if (filterType === "SkillLevel") {
                            skillLevelFilterKey = filterKey;
                        }
                        if (filterType === "Prices") {
                            priceFilterKey = filterKey;
                        }
                    });

                    selectedEventIds = $J("#selected-event-ids").val().toString();

                    var postData = {
                        CurrentExploreCategoryPageId: sourceId,
                        CurrentFarmFeedDataSourceId: sourceId,
                        CurrentPageId: currentPageId,
                        PageIndex: 0,
                        PageSize: 0,
                        ApplyFilter: true,
                        SelectedPillar: selectedPillar,
                        SelectedLocation: locationFilterKey,
                        SelectedTimeline: timeLineFilterKey,
                        SelectedSkillLevel: skillLevelFilterKey,
                        SelectedPriceRange: priceFilterKey,
                        Keyword: keyword,
                        SelectedEventIds: selectedEventIds,
                        IsEventFeed: isEventFeed
                    };

                    _exploreScope.getExploreFeed(postData, tileContainer, true);
                }
            },

            initExploreListingFeedLoadMore: function () {
                var $exploreListingFeedContainer = $J('.explore-content-feed');
                if ($exploreListingFeedContainer && $exploreListingFeedContainer.length > 0) {
                    var $loadMore = $J('.explore-content-feed .explore-load-more-feed a');
                    $loadMore.on('click', function (e) {
                        e.preventDefault();

                        var sliceStartIndex = parseInt($J(this).attr('data-slice-start'));
                        var sliceEndIndex = parseInt($J(this).attr('data-slice-end'));
                        var sliceMaxIndex = parseInt($J(this).attr('data-slice-max'));
                        var currentDisplayedTiles = parseInt($J(this).attr('data-slice-next'));
                        var pageSize = parseInt($J(this).attr('data-page-size'));
                        var hitCounter = parseInt($J(this).attr('data-hit-counter'));

                        var nextDataToDisplay = currentDisplayedTiles - pageSize;

                        var tilesTypeForLoadMore = $J(this).attr('data-tiles-type');
                        var tilesTypeForLoadMoreText = $J(this).attr('data-tiles-counter-text');

                        //INC0800775 -- when looking in ExploreContentFeedService, the plurals are already defined there.
                        //Javascript should just be adding the data-tiles-counter-text value
                        //var tilesCounterForLoadMore = nextDataToDisplay > 1 ? tilesTypeForLoadMoreText + 's' : tilesTypeForLoadMoreText;

                        $exploreListingFeedContainer = $J(this).closest('.explore-content-feed');
                        if (sliceEndIndex <= sliceMaxIndex) {
                            if (sliceStartIndex === sliceEndIndex) {
                                $exploreListingFeedContainer.find('li').slice(sliceStartIndex).removeClass('hide--me');
                            }
                            else {
                                $exploreListingFeedContainer.find('li').slice(sliceStartIndex, sliceEndIndex).removeClass('hide--me');
                            }

                            if (pageSize > 6 && hitCounter === 0) {
                                pageSize++;
                                $J(this).attr('data-page-size', pageSize);
                            }

                            $J(this).attr('data-slice-start', sliceEndIndex);
                            $J(this).attr('data-slice-end', sliceEndIndex + pageSize <= sliceMaxIndex ? sliceEndIndex + pageSize : sliceMaxIndex);
                            $J(this).attr('data-slice-next', nextDataToDisplay);

                            $J($exploreListingFeedContainer).slideDown(500);

                            if (nextDataToDisplay > 0) {
                                var loadMoreText = "<span>Load more " + tilesTypeForLoadMore + "</span><br>" + "(" + nextDataToDisplay + ") " + tilesTypeForLoadMoreText + " left";
                                $J(this).html(loadMoreText);
                            }
                            else {
                                $J(this).parent().addClass('hide--me');
                            }

                            hitCounter++;
                            $J(this).attr('data-hit-counter', hitCounter);

                            canonHelper.tileMarginFix($exploreListingFeedContainer);
                        }
                    });
                }
            },

            initEventContentFeed: function () {
                function renderEventFeedItems(postData, componentContainer, resultContainer, isPaging) {
                    canonHelper.showSpinner();
                    var request = canonHelper.addAntiForgeryToken(postData);
                    var post = $.post('/content-tile/event/getevents', request);
                    var loadMoreButtonContainer = $J(componentContainer).parent().find(".event-feed-load-more-feed");
                    var template = $J(componentContainer).find('.event-content-feed-container-template').html();
                    var noResultsFoundContainer = $J(componentContainer).find(".no-result-found-container");
                    if (!noResultsFoundContainer.hasClass("hide--me")) {
                        noResultsFoundContainer.addClass("hide--me");
                    }
                    post.done(function (data) {
                        loadMoreButtonContainer.addClass("hide--me");
                        if (data) {
                            if (!isPaging) {
                                renderEventFeedFilter(componentContainer, data);
                                _exploreScope.initEventContentFeed();
                            }
                            if (data.EventContentSkinnyTiles && data.EventContentSkinnyTiles.length > 0) {
                                var result = Mustache.to_html(template, data);
                                if (isPaging) {
                                    $J(resultContainer).append(result);
                                }
                                else {
                                    $J(resultContainer).html(result);
                                }
                            }
                            else if (data.CurrentPageIndex <= 0) {
                                $J(resultContainer).html("");
                                if (noResultsFoundContainer.hasClass("hide--me")) {
                                    noResultsFoundContainer.removeClass("hide--me");
                                }
                            }
                            if (data.IsNextPageAvailable) {
                                loadMoreButtonContainer.removeClass("hide--me");
                                loadMoreButtonContainer.find("a").data("current-page", data.CurrentPageIndex);
                                loadMoreButtonContainer.find("a").data("is-next-page-available", data.IsNextPageAvailable);
                                loadMoreButtonContainer.find("a").html("<span>Load more events</span><br />(" + data.NextItemToDisplayed + " events left)");
                            }
                        }

                        canonHelper.hideSpinner();
                    });

                    post.fail(function () {
                        canonHelper.hideSpinner();
                    });
                }

                function renderEventFeedFilter(componentContainer, responseData) {
                    if (responseData.FeedFilterOptions) {
                        var resultContainer = $J(componentContainer).find(".event-feed-filter-options");
                        var template = $J(componentContainer).find('.event-content-feed-filter-container-template').html();
                        var result = Mustache.to_html(template, responseData);
                        $J(resultContainer).html(result);
                    }
                }

                function isMobielDevice() {
                    if (screen.width <= 700) {
                        return true;
                    }

                    return false;
                }

                function getPostRequestData(dataSourceId, currentPageId, currentPageIndex, selectedValue, eventStartDate, eventEndDate, reloadFilter, immediateAvailableEventStartDate) {
                    var postData = {
                        dataSourceId: dataSourceId,
                        currentPageId: currentPageId,
                        pageIndex: currentPageIndex,
                        selectedFilter: selectedValue,
                        eventStartDate: eventStartDate,
                        eventEndDate: eventEndDate,
                        reloadFilter: reloadFilter,
                        isMobile: isMobielDevice(),
                        immediateAvailableEventStartDate: immediateAvailableEventStartDate
                    };

                    return postData;
                }


                if ($J(".event-feed-filter-date-by").length > 0) {
                    $J(".event-feed-filter-date-by").off("change");
                    $J(".event-feed-filter-date-by").on("change", function () {
                        var selectedItem = $J(this).find(":selected");
                        var selectedValue = selectedItem.val();
                        var $componentContainer = $J(this).closest(".event-content-feed");
                        if (selectedValue) {
                            var monthOrDaycontainer = $componentContainer.find(".event-feed-container-type");
                            monthOrDaycontainer.removeClass("month").removeClass("day");
                            monthOrDaycontainer.addClass(selectedValue);
                            var dataSourceId = $componentContainer.data('datasource');
                            var currentPageId = $componentContainer.data('current-id');
                            var immediateAvailableEventStartDate = $componentContainer.data('imd-available-event-start-date');
                            var currentPageIndex = 0;
                            var reloadFilter = true;
                            var postData = getPostRequestData(dataSourceId, currentPageId, currentPageIndex, selectedValue, selectedItem.data("start-date"), selectedItem.data("end-date"), reloadFilter, immediateAvailableEventStartDate);
                            renderEventFeedItems(postData, $componentContainer, $componentContainer.find(".event-content-feed-items-container"), false);
                        }
                    });
                }

                if ($J(".event-feed-load-more-feed").length > 0) {
                    $J(".event-feed-load-more-feed a").off("click");
                    $J(".event-feed-load-more-feed a").on("click", function (e) {
                        e.preventDefault();
                        e.stopPropagation();
                        var $componentContainer = $J(this).parent().parent().find(".event-content-feed");
                        var isNextPageAvailable = $J(this).data("is-next-page-available");
                        var selectedFilterItem = $componentContainer.find(".event-feed-filter-options ul li.active");
                        var selectedValue = $componentContainer.find(".event-feed-filter-date-by").find(":selected").val();
                        if (selectedFilterItem.length > 0) {
                            var dataSourceId = $componentContainer.data('datasource');
                            var currentPageId = $componentContainer.data('current-id');
                            var immediateAvailableEventStartDate = $componentContainer.data('imd-available-event-start-date');
                            var currentPageIndex = isNextPageAvailable ? $J(this).data("current-page") + 1 : $J(this).data("current-page");
                            var reloadFilter = false;
                            var postData = getPostRequestData(dataSourceId, currentPageId, currentPageIndex, selectedValue, selectedFilterItem.data("start"), selectedFilterItem.data("end"), reloadFilter, immediateAvailableEventStartDate);
                            renderEventFeedItems(postData, $componentContainer, $componentContainer.find(".event-content-feed-items-container"), true);
                        }
                    });
                }

                if ($J(".event-feed-filter-options").length > 0) {
                    $J(".event-feed-filter-options ul li").off("click");
                    $J(".event-feed-filter-options ul li").on("click", function (e) {
                        e.preventDefault();
                        e.stopPropagation();
                        var $this = $J(this);
                        if (!$this.hasClass("active") && !$this.hasClass("disabled")) {
                            $J(".event-feed-filter-options ul li").removeClass("active");
                            $this.addClass("active");
                            var $componentContainer = $this.closest(".event-content-feed");
                            var selectedFilterItem = $this;
                            var selectedValue = $componentContainer.find(".event-feed-filter-date-by").find(":selected").val();
                            if (selectedFilterItem.length > 0) {
                                var dataSourceId = $componentContainer.data('datasource');
                                var currentPageId = $componentContainer.data('current-id');
                                var immediateAvailableEventStartDate = $componentContainer.data('imd-available-event-start-date');
                                var currentPageIndex = 0;
                                var reloadFilter = false;
                                var postData = getPostRequestData(dataSourceId, currentPageId, currentPageIndex, selectedValue, selectedFilterItem.data("start"), selectedFilterItem.data("end"), reloadFilter, immediateAvailableEventStartDate);
                                renderEventFeedItems(postData, $componentContainer, $componentContainer.find(".event-content-feed-items-container"), false);
                            }
                        }
                    });
                }

                if ($J(".event-feed-filter-nav").length > 0) {
                    $J(".event-feed-filter-nav").off("click");
                    $J(".event-feed-filter-nav.active").on("click", function (e) {
                        e.preventDefault();
                        e.stopPropagation();
                        var $this = $J(this);
                        if ($this.hasClass("active")) {
                            var $componentContainer = $this.closest(".event-content-feed");
                            var selectedFilterItem = $this;
                            var selectedValue = $componentContainer.find(".event-feed-filter-date-by").find(":selected").val();
                            if (selectedFilterItem.length > 0) {
                                var dataSourceId = $componentContainer.data('datasource');
                                var currentPageId = $componentContainer.data('current-id');
                                var immediateAvailableEventStartDate = $componentContainer.data('imd-available-event-start-date');
                                var currentPageIndex = 0;
                                var reloadFilter = true;
                                var postData = getPostRequestData(dataSourceId, currentPageId, currentPageIndex, selectedValue, selectedFilterItem.data("start"), selectedFilterItem.data("end"), reloadFilter, immediateAvailableEventStartDate);
                                renderEventFeedItems(postData, $componentContainer, $componentContainer.find(".event-content-feed-items-container"), false);
                            }
                        }
                    });
                }
            }
        };

        return _exploreScope;

    })();

    $J(document).ready(function () {
        if (canonHelper !== undefined) {
            explore.init();
        }
    });
})(jQuery);;
(function ($J, window) {
    var externalEvent = (function () {
        var checkoutWidgets = [];
        var gaClientId;
        var _externalEventScope = {
            init: function () {
                //this.addToCalendar();
                this.initCheckOutButton();
                this.initShareButton();
            },

            // Eventbrite: Add to calendar

            //addToCalendar: function () {
            //    var $externalEventInfoContainer = $J('.event-info-container');
            //    if ($externalEventInfoContainer && $externalEventInfoContainer.length > 0) {
            //        var $addToCalendar = $J('.add-to-calendar');
            //        $addToCalendar.on('click', function (e) {
            //            e.preventDefault();
            //            var $currentTarget = e.currentTarget;
            //            var eventTitle = $currentTarget.getAttribute("data-event-title");
            //            var eventLocation = $currentTarget.getAttribute("data-event-location");
            //            var eventStartDate = $currentTarget.getAttribute("data-event-start");
            //            var eventEndDate = $currentTarget.getAttribute("data-event-end");

            //            var cal = ics();
            //            cal.addEvent(eventTitle, eventTitle, eventLocation, eventStartDate, eventEndDate);
            //            cal.download('calendar', '.ics');
            //        });
            //    }
            //},

            // Embed a button
            initCheckOutButton: function () {
                var $externalEventCheckoutContainer = $J('.event-checkout-button-container');
                if ($externalEventCheckoutContainer && $externalEventCheckoutContainer.length > 0) {
                    var $checkoutButton = $J('.event-checkout-button');
                    $checkoutButton.on('click', function (e) {
                        e.preventDefault();

                        var eventId = $checkoutButton.attr('data-series-id');
                        if (!checkoutWidgets.includes(eventId)) {
                            window.EBWidgets.createWidget({
                                widgetType: 'checkout',
                                eventId: eventId,
                                modal: true,
                                modalTriggerElementId: 'eventbrite-widget-modal-trigger-' + eventId,
                                googleAnalyticsClientId: gaClientId,
                            });
                            checkoutWidgets.push(eventId);
                        }
                    });
                }

            },

            initShareButton: function () {
                var $externalEventShareContainer = $J('.hero-banner-share-modal-container');
                if ($externalEventShareContainer && $externalEventShareContainer.length > 0) {
                    var $shareButton = $J('.hero-banner-share');
                    $shareButton.on('click', function (e) {
                        e.preventDefault();
                        var $shareModalEl = $J($shareButton).parent().find('.share-modal');
                        if ($shareModalEl.hasClass('hide--me')) {
                            $shareModalEl.removeClass('hide--me');
                        }
                    });
                }

                var $externalEventShareContent = $J('.share-modal-content');
                if ($externalEventShareContent && $externalEventShareContent.length > 0) {
                    var $closeButton = $J('.share-modal-close');
                    $closeButton.on('click', function (e) {
                        e.preventDefault();
                        var $shareModalEl = $J($externalEventShareContent).parent().parent().find('.share-modal');
                        if (!$shareModalEl.hasClass('hide--me')) {
                            $shareModalEl.addClass('hide--me');
                        }
                    });
                }
            }
        };

        return _externalEventScope;

    })();

    $J(document).ready(function () {
        if (canonHelper !== undefined) {
            externalEvent.init();
        }
    });
})(jQuery, window);;
(function ($J) {
    var cashBack = (function () {
        var _cashBackScope = {
            init: function () {
                this.initCashbackForms();
                this.initCharityCashBack();
                this.initGiftRedemptionForm();
                this.initCompetitionRedemptionForm();
                this.initCashbackProductFeedFilter();
                this.initCashbackProductFeedLoadMore();
                this.initCashbackProductFeedByKeyword();
                this.initCashBackTilesHatch();
            },

            splitAddressGooglePlace: function (textboxElementId) {
                var ignoreValidation = $J("#PurchasedOnline").val() === "true";
                var textBoxElement = $('#' + textboxElementId);
                var autocomplete;

                if (typeof google === 'object' && typeof google.maps === 'object') {
                    initAutocomplete();
                }

                function initAutocomplete() {
                    autocomplete = new google.maps.places.Autocomplete((textBoxElement[0]), { types: ["geocode"], componentRestrictions: { country: ($('body.region-nz') && $('body.region-nz').length > 0) ? 'nz' : 'au' } });
                    autocomplete.addListener('place_changed', fillInAddress);
                }

                function fillInAddress() {
                    var place = autocomplete.getPlace();

                    var fulladdressInputElement = $(textBoxElement).closest('form').find('.cashback-retailer-fulladdress');
                    var addressInputElement = $(textBoxElement).closest('form').find('.cashback-retailer-address');
                    var stateInputElement = $(textBoxElement).closest('form').find('.cashback-retailer-state');
                    var suburbInputElement = $(textBoxElement).closest('form').find('.cashback-retailer-suburb');
                    var postcodeInputElement = $(textBoxElement).closest('form').find('.cashback-retailer-postcode');

                    var fullAddress = $(textBoxElement).val();

                    $(fulladdressInputElement).val(fullAddress);
                    $(addressInputElement).val('');
                    $(stateInputElement).val('');
                    $(suburbInputElement).val('');
                    $(postcodeInputElement).val('');

                    var address = '';
                    var suburb = '';
                    var state = '';
                    var postcode = '';

                    if (!ignoreValidation) {
                        if (place) {
                            $(textBoxElement).removeClass('invalid');
                            $(textBoxElement).parent().find('.field-validation-valid').text("");
                        }
                    }

                    if (place && place.address_components) {
                        placeSelected = fullAddress;
                        for (var i = 0; i < place.address_components.length; i++) {
                            var addressType = place.address_components[i].types[0];

                            if (addressType === 'street_number') {
                                address = place.address_components[i]['short_name'];
                            }
                            else if (addressType === 'route') {
                                address += " " + place.address_components[i]['long_name'];
                            }
                            else if (addressType === 'locality') {
                                suburb = place.address_components[i]['long_name'];
                            }
                            else if (addressType === 'administrative_area_level_1') {
                                state = place.address_components[i]['long_name'];
                            }
                            else if (addressType === 'postal_code') {
                                postcode = place.address_components[i]['short_name'];
                            }
                        }
                    }

                    if (address) {
                        $(addressInputElement).val(address);
                    }

                    if (state) {
                        $(stateInputElement).val(state);
                    }

                    if (suburb) {
                        $(suburbInputElement).val(suburb);
                    }

                    if (postcode) {
                        $(postcodeInputElement).val(postcode);
                    }
                }
            },

            cashBackHelper: {
                initUploadReceiptHandler: function ($form) {
                    var $uploadReceiptRadio = $form.find("#upload-receipt-yes");
                    if ($uploadReceiptRadio.length > 0) {
                        var $postReceiptContainer = $form.find(".post-receipt");
                        var $uploadReceiptContainer = $form.find(".upload-receipt");
                        var isUploadChecked = $form.find('#upload-receipt-yes:checked').length > 0;
                        var $proofOfPurchaseIdEl = $form.find('#ProofOfPurchaseId');
                        $postReceiptContainer.hide();

                        if (!isUploadChecked) {
                            $uploadReceiptContainer.hide();
                        } else {
                            $uploadReceiptContainer.show();
                            if ($proofOfPurchaseIdEl.val().length === 0) {
                                $uploadReceiptContainer.find("[mandatory]").attr("required", "true");
                            }

                            $postReceiptContainer.hide();
                            $postReceiptContainer.find("[mandatory]").removeAttr("required");
                        }

                        $form.find("#upload-receipt-yes,#upload-receipt-no").click(function () {
                            if ($J(this).val().toLowerCase() === "upload" || $J(this).val().toLowerCase() === "true") {
                                $uploadReceiptContainer.show();
                                if ($proofOfPurchaseIdEl.val().length === 0) {
                                    $uploadReceiptContainer.find("[mandatory]").attr("required", "true");
                                }

                                $postReceiptContainer.hide();
                                $postReceiptContainer.find("[mandatory]").removeAttr("required");
                            }
                            else {
                                $postReceiptContainer.show();
                                $postReceiptContainer.find("[mandatory]").attr("required", "true");
                                $uploadReceiptContainer.hide();
                                $uploadReceiptContainer.find("[mandatory]").removeAttr("required");
                            }
                        });
                    }

                    var $uploadCashBackReceiptInput = $form.find('.cashback-upload-receipt');
                    if ($uploadCashBackReceiptInput.length > 0) {
                        $uploadCashBackReceiptInput.off('change');
                        $uploadCashBackReceiptInput.on('change', function () {
                            if ($uploadCashBackReceiptInput.is(':visible')) {
                                if (typeof FileReader !== "undefined" && $(this)[0].files && $(this)[0].files[0]) {
                                    var size = ($(this)[0].files[0].size) / 1024; //Kilobyte
                                    if (size > 5120) {
                                        if (!$(this).hasClass('invalid')) {
                                            $(this).addClass('invalid');
                                        }
                                        $(this).closest(".file").next('.field-validation-valid').show();
                                        $(this).closest(".file").next('.field-validation-valid').text("Maximum file size allowed is 5mb.");
                                        $(this).parent().find(".after").html("Click here to upload file.");
                                    }
                                    else {
                                        $(this).removeClass('invalid');
                                        $(this).closest(".file").next('.field-validation-valid').hide();
                                        $(this).closest(".file").next('.field-validation-valid').text("");
                                        var uploadedValue = $(this).val()
                                        var lastIndex = uploadedValue.lastIndexOf("\\");
                                        if (lastIndex >= 0) {
                                            $(this).parent().find(".after").html(uploadedValue.substring(lastIndex + 1));
                                        }
                                    }
                                }
                                else {
                                    $(this).removeClass('invalid');
                                }
                            }
                        });
                    }
                },
                initPaymentMethodHandler: function ($form) {
                    var $eftPaymentOption = $form.find("#payment-option-eft");
                    var $chequePaymentOption = $form.find("#payment-option-chq");
                    var $eftNZAccountNumber = $form.find(".EFTAccountNumbernz");
                    var $eftAccountNumber = $form.find("#EFTAccountNumber");
                    var $bankName = $form.find("#hdn_BankName");
                    var $bsbBankName = $form.find(".BSBBankName");
                    var $eftBsb = $form.find("#EFTBSB");

                    if ($eftPaymentOption.length > 0) {
                        var $chequeSection = $form.find(".cheque-section");
                        var $eftSection = $form.find(".eft-section");
                        $chequeSection.hide();
                        $eftSection.hide();

                        $form.find("#payment-option-eft, #payment-option-chq").on('click', function () {
                            if ($J(this).attr('id').toLowerCase() === "payment-option-eft") {
                                $eftSection.show();

                                $eftSection.find("[mandatory]").attr("required", "true");

                                $chequeSection.hide();
                                $chequeSection.find("[mandatory]").removeAttr("required");
                                $chequeSection.find(".invalid").removeClass("invalid");
                                $chequeSection.find('input:text').val('');
                                $chequeSection.find('input[type=number]').val('');
                                $chequeSection.find('select').val('');

                                if ($eftNZAccountNumber.length > 0) {
                                    $eftNZAccountNumber.attr("pattern", "^[0-9]{2}-?[0-9]{4}-?[0-9]{7}-?[0-9]{2}$");
                                }
                            }
                            else {
                                $chequeSection.show();
                                $chequeSection.find("[mandatory]").attr("required", "true");

                                $eftSection.hide();
                                $eftSection.find("[mandatory]").removeAttr("required");
                                $eftSection.find(".invalid").removeClass("invalid");
                                $eftSection.find('input:text').val('');
                                $eftSection.find('input[type=number]').val('');
                                $eftSection.find('select').val('');

                                $bankName.val('');

                                if ($("span[data-valmsg-for='EFTBSB']").html() !== '') {
                                    $("span[data-valmsg-for='EFTBSB']").html('');
                                }

                                if ($eftNZAccountNumber.length > 0) {
                                    $eftNZAccountNumber.removeAttr("pattern");
                                }
                            }
                        });
                    }

                    if ($eftPaymentOption.attr("checked")) {
                        $eftPaymentOption.prop("checked", true).trigger("click");
                    }
                    else if ($chequePaymentOption.attr("checked")) {
                        $chequePaymentOption.prop("checked", true).trigger("click");
                    }

                    if ($eftNZAccountNumber.length > 0) {
                        MaskedInput({
                            elm: document.getElementById('EFTAccountNumber'), // select only by id
                            format: '__-____-_______-__',
                            separator: '-'
                        });
                    }

                    /* For checking NZ bank we have used a thirdparty validator
                    Source : https://www.npmjs.com/package/nz-bank-account-validator
                    */
                    $eftNZAccountNumber.on("blur", function () {
                        var accountNumber = $eftAccountNumber.val();
                        console.log(accountNumber);
                        var nzBankAccountValidator = window['NZ-Bank-Account-Validator'];
                        var isvalid = nzBankAccountValidator.validate(accountNumber);
                        var validateField = $eftAccountNumber.closest('.field').find('.field-validation-valid');

                        if (isvalid) {
                            validateField.text('');
                            $eftAccountNumber.removeClass("invalid");
                            if (validateField.hasClass("error")) {
                                validateField.removeClass("error");
                            }
                            if (!validateField.hasClass("success")) {
                                validateField.addClass("success");
                            }
                        }
                        else {

                            validateField.text("Please enter a valid New Zealand Bank account number.");
                            $eftAccountNumber.addClass("invalid");


                            if (!validateField.hasClass("error")) {
                                validateField.addClass("error");
                            }
                            if (validateField.hasClass("success")) {
                                validateField.removeClass("success");
                            }
                        }
                    });

                    $bsbBankName.on("blur", function () {
                        var bsb = $eftBsb.val();
                        var currentForm = $J(this).closest('form');
                        $bankName.val('');
                        if ($("span[data-valmsg-for='EFTBSB']").html() != '')
                            $("span[data-valmsg-for='EFTBSB']").html('');
                        if (bsb && bsb.length > 0) {
                            canonHelper.showSpinner();
                            $J.ajax({
                                type: 'POST',
                                url: "/canonhub/cashbackform/getbankname?bsbCode=" + bsb,
                                contentType: 'application/json',
                                error: function (request, status, error) {
                                    canonHelper.hideSpinner();
                                    $eftBsb.addClass("invalid");
                                    $eftBsb.closest('.field').find('.field-validation-valid').text("Invalid BSB");
                                    _cashBackScope.cashBackHelper.onError(request, status, error, $J(currentForm));
                                }
                            }).done(function (response) {
                                var validateField = $eftBsb.closest('.field').find('.field-validation-valid');
                                if (response == '') {
                                    if (!validateField.hasClass("error")) {
                                        validateField.addClass("error");
                                    }
                                    if (validateField.hasClass("success")) {
                                        validateField.removeClass("success");
                                    }
                                    validateField.text("Invalid BSB");
                                    $eftBsb.addClass("invalid");
                                }
                                else {
                                    validateField.text(response);
                                    $eftBsb.removeClass("invalid");
                                    if (validateField.hasClass("error")) {
                                        validateField.removeClass("error");
                                    }
                                    if (!validateField.hasClass("success")) {
                                        validateField.addClass("success");
                                    }
                                }
                                $eftBsb.show();
                                canonHelper.hideSpinner();
                            });
                        }
                    })
                },
                initPurchaseLocationHandler: function ($form) {
                    var $purchaseOnlineOption = $form.find("#PurchasedOnline");
                    if ($purchaseOnlineOption.length > 0) {

                        $purchaseOnlineOption.on("change", function () {
                            var selectedItem = $purchaseOnlineOption.find("option:selected");
                            var isPurchasedOnline = $J(selectedItem).val() === 'true';
                            var isPurchasedModeEmpty = $J(selectedItem).val().length === 0;
                            var defaultRetailerNameText = isPurchasedOnline ? "Select a website" : "Select a retailer";
                            $('#retailer-name option:first').text(defaultRetailerNameText);

                            var retailerLocationElement = $form.find("#retailer-location");
                            var addressInputElement = $form.find('.cashback-retailer-address');
                            var stateInputElement = $form.find('.cashback-retailer-state');
                            var suburbInputElement = $form.find('.cashback-retailer-suburb');
                            var postcodeInputElement = $form.find('.cashback-retailer-postcode');

                            if (!isPurchasedModeEmpty) {
                                if (isPurchasedOnline) {
                                    if ($(retailerLocationElement).hasClass('invalid')) {
                                        $(retailerLocationElement).removeClass('invalid');
                                    }

                                    $(retailerLocationElement).parent().find('.field-validation-valid').text("");

                                    $(retailerLocationElement).val('Online');
                                    $(retailerLocationElement).removeClass('invalid');
                                    $(retailerLocationElement).removeAttr('disabled');
                                    $(retailerLocationElement).attr('disabled', '');

                                    $(addressInputElement).val('online');
                                    $(stateInputElement).val('online');
                                    $(suburbInputElement).val('online');
                                    $(postcodeInputElement).val('online');

                                }
                                else {
                                    $(retailerLocationElement).val('');
                                    if (!$(retailerLocationElement).hasClass('invalid')) {
                                        $(retailerLocationElement).addClass('invalid');
                                    }
                                    $(retailerLocationElement).removeAttr('disabled');

                                    $(addressInputElement).val('');
                                    $(stateInputElement).val('');
                                    $(suburbInputElement).val('');
                                    $(postcodeInputElement).val('');
                                }
                            }
                            else {
                                $(retailerLocationElement).val('');
                                $(retailerLocationElement).removeClass('invalid');
                                $(retailerLocationElement).removeAttr('disabled');
                                $(retailerLocationElement).attr('disabled', '');

                                $(addressInputElement).val('');
                                $(stateInputElement).val('');
                                $(suburbInputElement).val('');
                                $(postcodeInputElement).val('');
                            }
                        });
                    }

                    var $retailerLocation = $form.find("#retailer-location");
                    if ($retailerLocation.length > 0) {
                        _cashBackScope.splitAddressGooglePlace("retailer-location");

                        $retailerLocation.on('blur', function () {
                            validateRetailerLocation($(this));
                        });

                        $retailerLocation.on('keypress', function (e) {
                            if (e.which === 13) {
                                validateRetailerLocation($(this));
                            }
                        });

                        function validateRetailerLocation(el) {
                            if ($(el).val().length > 0 && placeSelected.length > 0) {
                                if ($(el).val() !== placeSelected) {
                                    if (!$(el).hasClass('invalid')) {
                                        $(el).addClass('invalid');
                                    }
                                }
                                else {
                                    $(el).removeClass('invalid');
                                }
                            }

                            if ($(el).hasClass('invalid')) {
                                $(el).parent().find('.field-validation-valid').text("Please select valid address from selection.");
                            }
                            else {
                                $(el).parent().find('.field-validation-valid').text("");
                            }
                        }
                    }
                },
                initPurchaseDateValidation: function ($form) {
                    var $purchaseDateInput = $form.find('.cashback-date-bought');
                    if ($purchaseDateInput.length > 0) {

                        $form.find('input[type="submit"]').on('click', function () {
                            var invalid = $(this).closest('form').find('input:invalid')[0];
                            if (invalid) {
                                $(invalid).focus();
                            }
                        });

                        $purchaseDateInput.each(function () {

                            $(this).removeClass("hasDatepicker").removeAttr('id');

                            var minDate = $(this).attr('data-min-date');
                            var maxDate = $(this).attr('data-max-date');

                            var maxDateMoment = moment(maxDate, "YYYY-MM-DD");
                            var isMaxDateFutureDate = moment().startOf('day').diff(maxDateMoment.startOf('day'), 'days') < 0;
                            if (isMaxDateFutureDate) {
                                maxDate = moment().format('YYYY-MM-DD');
                            }

                            $(this).datepicker("destroy");

                            $(this).parent().find('img.ui-datepicker-trigger').remove();

                            $(this).datepicker({
                                showOn: "both",
                                buttonImage: "/images/svg/icon-datepicker.svg",
                                buttonImageOnly: true,
                                buttonText: "Select date",
                                dateFormat: "dd/mm/yy",
                                minDate: new Date(minDate),
                                maxDate: new Date(maxDate),
                                onSelect: function () {
                                    validateDatePicker($(this));
                                }
                            });
                        });

                        $purchaseDateInput.on('blur', function () {
                            validateDatePicker($(this));
                        });

                        function validateDatePicker(el) {
                            var minDate = moment($(el).attr('data-min-date'), 'YYYY-MM-DD');
                            var maxDate = moment($(el).attr('data-max-date'), 'YYYY-MM-DD');

                            var maxDateMoment = moment(maxDate, "YYYY-MM-DD");
                            var isMaxDateFutureDate = moment().startOf('day').diff(maxDateMoment.startOf('day'), 'days') < 0;
                            if (isMaxDateFutureDate) {
                                maxDate = moment();
                            }

                            var currentValue = moment($(el).val(), "DD/MM/YYYY");
                            if (currentValue.isValid()) {
                                if (currentValue < minDate || currentValue > maxDate) {
                                    $(el).parent().find('.field-validation-valid').text("Date bought must be within the purchase period and equal to or earlier than today's date");
                                    if ($(el).hasClass('valid')) {
                                        $(el).removeClass('valid');
                                    }

                                    if (!$(el).hasClass('invalid')) {
                                        $(el).addClass('invalid');
                                    }
                                }
                                else {
                                    $(el).removeClass('invalid');
                                    $(el).addClass('valid');
                                    $(el).parent().find('.field-validation-valid').text('');
                                }
                            }
                        }
                    }
                },
                initEmailValidation: function ($form) {
                    var $cashbackEmail = $form.find('.cashback-email');
                    if ($cashbackEmail.length > 0) {

                        $('.cashback-email').on('keypress', function () {
                            validateEmail($(this));
                        });

                        $('.cashback-email').blur(function () {
                            validateEmail($(this));
                        });

                        if ($cashbackEmail.val() != null && $cashbackEmail.val().length > 0) {
                            if (validateEmail($cashbackEmail)) {
                                window.onload = function () {
                                    $cashbackEmail[0].setCustomValidity('');
                                }
                            }
                        }

                        function validateEmail(el) {
                            var mailformat = /^([a-z\d\-_\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")@(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;
                            if ($(el).val().match(mailformat)) {
                                $(el).parent().find('.field-validation-valid').text('');
                                $(el).attr('valid', '');
                                $(el).removeClass('invalid');
                                return true;
                            }
                            else {
                                var errorMessage = $(el).val().length > 0 ? "Please match the requested format." : "Please fill out this field.";
                                $(el).parent().find('.field-validation-valid').text(errorMessage);
                                $(el).removeAttr('valid');
                                if (!$(el).hasClass('invalid')) {
                                    $(el).addClass('invalid');
                                }

                                return false;
                            }
                        }
                    }
                },
                initStandardTextFieldValidation: function ($form) {
                    var $cashbackTextField = $form.find('.cashback-textfield');
                    if ($cashbackTextField.length > 0) {
                        if ($cashbackTextField.val() != null && $cashbackTextField.val().length > 0) {
                            validateTextFields($($cashbackTextField));
                        }

                        $cashbackTextField.on('keypress', function () {
                            validateTextFields($(this));
                        });

                        $cashbackTextField.on('blur', function () {
                            validateTextFields($(this));
                        });

                        function validateTextFields(el) {
                            var mailformat = /^[a-zA-Z ]+$/;
                            if ($(el).val().match(mailformat)) {
                                $(el).parent().find('.field-validation-valid').text('');
                                $(el).removeClass('invalid');
                            }
                            else {
                                var errorMessage = "Please use standard letters and spaces only.";
                                $(el).parent().find('.field-validation-valid').text(errorMessage);

                                if (!$(el).hasClass('invalid')) {
                                    $(el).addClass('invalid');
                                }
                            }
                        }
                    }
                },
                initAddressTextFieldValidation: function ($form) {
                    var $addressTextField = $form.find('.address-field');
                    if ($addressTextField.length > 0) {
                        if ($addressTextField.val() != null && $addressTextField.val().length > 0) {
                            validateTextFields($($addressTextField));
                        }

                        $addressTextField.on('keypress', function () {
                            validateTextFields($(this));
                        });

                        $addressTextField.on('blur', function () {
                            validateTextFields($(this));
                        });

                        function validateTextFields(el) {
                            var regex = new RegExp(/\b(?:p\.?\s*o\.?|post\s+office)(\s+)?(?:box|[0-9]*)?\b/igm);
                            if ($(el).val().match(regex)) {
                                var errorMessage = "Address cannot be a PO box.";
                                $(el).parent().find('.field-validation-valid').text(errorMessage);

                                if (!$(el).hasClass('invalid')) {
                                    $(el).addClass('invalid');
                                }
                            }
                            else {
                                $(el).parent().find('.field-validation-valid').text('');
                                $(el).removeClass('invalid');
                            }
                        }
                    }
                },
                onError: function (xhr, errorType, exception, currentForm) {
                    if ($J("#error-dialog").hasClass("ui-dialog-content")) {
                        $J("#error-dialog").dialog("destroy");
                    }
                    var responseText = "Sorry! We are experiencing technical difficulties, please contact our support team.";
                    var errorDialogElement = $J(currentForm).find("#error-dialog");
                    $J(errorDialogElement).html("");

                    try {
                        $J(errorDialogElement).html(responseText);
                        console.write(responseText);
                    } catch (e) {
                        $J(errorDialogElement).html(responseText);
                    }

                    $J(errorDialogElement).dialog({
                        title: "Error",
                        width: 700,
                        buttons: {
                            Close: function () {
                                $J(this).dialog('close');
                            }
                        }
                    });
                }
            },

            initCashbackForms: function () {
                canonHelper.hideSpinner();
                var $form = $J(".form-cash-back");
                $form.on('submit', function (e) {
                    if ($(this).find('input.invalid').length > 0) {
                        canonHelper.hideSpinner();
                        $(this).find('input.invalid')[0].focus();
                        e.preventDefault();
                    }
                    else {
                        canonHelper.showSpinner();
                    }
                });

                _cashBackScope.cashBackHelper.initUploadReceiptHandler($form);

                if ($form.find(".cashback-postcode").length > 0) {
                    $form.find(".cashback-postcode").on("keyup", function (e) {
                        $form.find("#ChequePostcode").val($J(this).val());
                    });
                }

                _cashBackScope.cashBackHelper.initPaymentMethodHandler($form);

                if ($J("#DoubleCashback").length > 0) {
                    $J(".double-cash").hide();
                    if (window.location.search.indexOf('dbl=true') > 0) {
                        $J(".double-cash").show();
                    }
                    $J("#DoubleCashback").change(function () {
                        var singlePrice = $J("#SingleCashBackValue").val();

                        var ignoreDoubleCashStdCalculationLogic = $J("#IgnoreDoubleCashStdCalculationLogic").val();
                        var extraCashBackAmount = $J("#ExtraCashBackAmount").val();
						
						var selectedItem = $J("#cashback-Product-name option:selected");
						
						var isIgnore = ignoreDoubleCashStdCalculationLogic && (ignoreDoubleCashStdCalculationLogic.toLowerCase() === 'true');


                        if ($(this).prop("checked")) {
							
							var amount = parseFloat(singlePrice) * 2;
						
							if (selectedItem.val() !== ""){
								
								var tileExtracashbackamountvalue = selectedItem.data("tile-extra-cash-back-amount-value");
								if (isIgnore && (extraCashBackAmount > 0 || tileExtracashbackamountvalue > 0))
								{
									if(tileExtracashbackamountvalue > 0){
										amount = parseFloat(singlePrice) + parseFloat(tileExtracashbackamountvalue);
									}
									else{
										amount = parseFloat(singlePrice) + parseFloat(extraCashBackAmount);
									}
									
								}
							}
                            
                            $J(".cashback-amt").html("$" + amount);
                            $J("#CashbackAmount").val(amount);
                            $J(".double-cash").show();
                        }
                        else {
                            $J(".cashback-amt").html("$" + singlePrice);
                            $J("#CashbackAmount").val(singlePrice);
                            $J(".double-cash").hide();
                        }
                    });
                }

                _cashBackScope.cashBackHelper.initPurchaseLocationHandler($form);

                if ($("#cashback-Product-name").length > 0) {
                    $J("#cashback-Product-name").change(function () {

                        var ignoreDoubleCashStdCalculationLogic = $J("#IgnoreDoubleCashStdCalculationLogic").val();
                        var extraCashBackAmount = $J("#ExtraCashBackAmount").val();
                        var selectedItem = $J("#cashback-Product-name option:selected");
                        var isDoublecashBack = $J("#DoubleCashback").prop("checked");
                        if (selectedItem.val() !== "") {
                            var cashbackValue = selectedItem.data("singlecashback-value");
                            var tileExtracashbackamountvalue = selectedItem.data("tile-extra-cash-back-amount-value");


                            var isIgnore = ignoreDoubleCashStdCalculationLogic && (ignoreDoubleCashStdCalculationLogic.toLowerCase() === 'true');


                            var amount = 0;
                            
                            if (isIgnore && (extraCashBackAmount > 0 || tileExtracashbackamountvalue > 0) )
                            {
								if(tileExtracashbackamountvalue > 0){
									amount = parseFloat(cashbackValue) + parseFloat(tileExtracashbackamountvalue);
								}
								else{
									amount = parseFloat(cashbackValue) + parseFloat(extraCashBackAmount);
								}
								
                            }
                            else{
                                amount =  cashbackValue * 2;
                            }
                            

                            var cashbackValueDisplay = isDoublecashBack ? amount : cashbackValue;
                            $J("#SingleCashBackValue").val(cashbackValue);
                            $J(".cashback-amt").html("$" + cashbackValueDisplay);
                            $J("#CashbackAmount").val(cashbackValueDisplay);
                            $J("#ProductId").val(selectedItem.data("product-tile-id"));
                        }
                        else {
                            $J("#SingleCashBackValue").val(0);
                            $J(".cashback-amt").html("$" + 0);
                            $J("#CashbackAmount").val(0);
                            $J("#ProductId").val(selectedItem.data("product-tile-id"));
                        }
                    });
                }

                _cashBackScope.cashBackHelper.initPurchaseDateValidation($form);
                _cashBackScope.cashBackHelper.initStandardTextFieldValidation($form);
                _cashBackScope.cashBackHelper.initAddressTextFieldValidation($form);
                _cashBackScope.cashBackHelper.initEmailValidation($form);
            },

            initCharityCashBack: function () {

                var $charityCashbackContainer = $J('.charity-cashback-container');
                var $mainContainer = $J('.charity-cashback-wizard');

                var navigateScreenToTop = function () {
                    $('html, body').animate({
                        scrollTop: $(".charity-cashback-wizard") - $("header").height()
                    }, 1000);
                }

                //Input validation
                function validateForm(container) {
                    if (container.length > 0) {
                        var formValid = true;
                        var submitButton = $J(container).find(".buttons button, .form-submit a");
                        container.find('input,.textarea-input').each(function () {
                            if (!$J(this)[0].checkValidity()) {
                                formValid = false;
                            }
                        });

                        container.find('input, .textarea-input').promise().done(function () {
                            if (formValid) {
                                if (!$J(submitButton).hasClass('valid')) {
                                    $J(submitButton).addClass('valid');
                                    $J(submitButton).removeAttr('disabled');
                                }
                            }
                            else {
                                $J(submitButton).removeClass('valid');
                                $J(submitButton).attr('disabled', 'disabled');
                            }
                        });
                    }
                }

                $charityCashbackContainer.find('input, .textarea-input').off('blur');
                $charityCashbackContainer.find('input, .textarea-input').on('blur', function () {
                    validateForm($charityCashbackContainer);
                });


                $charityCashbackContainer.find('input[type=number]').off('keypress');
                $charityCashbackContainer.find('input[type=number]').on('keypress', function () {
                    var currentElement = $J(this);
                    if (this.value.length >= this.maxLength) {
                        this.value = this.value.slice(0, this.maxLength - 1);
                    }
                });

                $charityCashbackContainer.find('input, .textarea-input').off('propertychange');
                $charityCashbackContainer.find('input, .textarea-input').on('propertychange', function () {
                    validateForm($charityCashbackContainer);
                });

                $charityCashbackContainer.find('input, .textarea-input').off('keyup');
                $charityCashbackContainer.find('input, .textarea-input').on('keyup', function () {
                    validateForm($charityCashbackContainer);
                });

                //Go back
                if ($charityCashbackContainer.find('.charity-cashback-back').length > 0) {
                    $J('.charity-cashback-back').off('click');
                    $J('.charity-cashback-back').on('click', function (e) {
                        e.preventDefault();
                        canonHelper.showSpinner();
                        var $currentElement = $J(this);
                        var token = canonHelper.getQueryString("token");
                        var postData = {
                            token: token
                        };

                        var data = canonHelper.addAntiForgeryToken(postData);
                        var post = $.post('/cashback/charitycashbackform/goback', data);

                        post.done(function (data) {
                            if (data) {
                                if (data.IsSuccessful != undefined && !data.IsSuccessful && data.ErrorMessage) {
                                    showGenericErrorModal();
                                }
                                else {
                                    $J($charityCashbackContainer).html(data);
                                    validateForm($charityCashbackContainer);
                                    _cashBackScope.initCharityCashBack();
                                }

                                canonHelper.hideSpinner();
                            }
                            else {
                                canonHelper.hideSpinner();
                                showGenericErrorModal();
                            }
                        });

                        post.fail(function () {
                            canonHelper.hideSpinner();
                        });


                    });
                }

                //Step-1
                if ($charityCashbackContainer.find('.charity-cashback-step1-form').length > 0) {
                    $charityCashbackContainer.find('.charity-cashback-step1-form').submit(false);

                    $charityCashbackContainer.find('.charity-cashback-step1-form').find('input, select').on('blur focus change keypress keyup', function (e) {
                        var errorMessage = "This field is required.";
                        var $this = $J(this);
                        $this.removeClass('invalid');
                        if ($(this).next().is(".field-validation-valid")) {
                            $(this).next().text("");
                        }
                        else if ($(this).attr("type") === "file") {
                            $(this).closest(".file").next('.field-validation-valid').text("");
                        }
                        else {
                            $(this).siblings('.field-validation-valid').text("");
                        }
                        var isFldValid = $this[0].checkValidity();
                        if (!isFldValid) {
                            if ($(this).attr("isemail")) {
                                errorMessage = "Please enter a valid email.";
                            }
                            if (!$this.hasClass('invalid')) {
                                $this.addClass('invalid');
                            }
                            if ($(this).next().is(".field-validation-valid")) {
                                $(this).next().text(errorMessage);
                            }
                            else if ($(this).attr("type") === "file") {
                                $(this).closest(".file").next('.field-validation-valid').text(errorMessage);
                            }
                            else {
                                $(this).siblings('.field-validation-valid').text(errorMessage);
                            }
                        }
                    });
                }

                var $uploadReceiptContainer = $charityCashbackContainer.find('div.cashback-upload-receipt');
                var isUploadRadioChecked = $charityCashbackContainer.find('.upload-receipt-yes:checked').length > 0;
                var $sendReceiptViaEmailContainer = $charityCashbackContainer.find('.cashback-email-receipt');
                var $uploadReceiptRadio = $charityCashbackContainer.find('#upload-receipt-yes');
                var $sendReceiptViaEmailRadio = $charityCashbackContainer.find('#upload-receipt-no');
                var $uploadReceiptInput = $charityCashbackContainer.find('input.cashback-upload-receipt');

                if (isUploadRadioChecked) {
                    $uploadReceiptInput.attr('required', 'true');
                }
                else {
                    $uploadReceiptInput.removeAttr('required');
                }

                if ($uploadReceiptRadio.length > 0) {
                    $uploadReceiptRadio.off('click');
                    $uploadReceiptRadio.on('click', function (e) {
                        $uploadReceiptContainer.removeClass('hide--me');
                        $sendReceiptViaEmailContainer.addClass('hide--me');
                        $J(this).attr('checked', 'checked');
                        $uploadReceiptInput.attr('required', 'true');
                    });
                }

                if ($sendReceiptViaEmailRadio.length > 0) {
                    $sendReceiptViaEmailRadio.off('click');
                    $sendReceiptViaEmailRadio.on('click', function (e) {
                        $sendReceiptViaEmailContainer.removeClass('hide--me');
                        $uploadReceiptContainer.addClass('hide--me');
                        $uploadReceiptInput.removeAttr('required');
                        $uploadReceiptInput.val('');
                        $uploadReceiptInput.closest('.field').find('.after').text('Upload a file');
                    });
                }

                var $purchaseDateInput = $charityCashbackContainer.find('.cashback-date-bought');
                if ($purchaseDateInput.length > 0) {

                    var minDate = $($purchaseDateInput).attr('data-min-date');
                    var maxDate = $($purchaseDateInput).attr('data-max-date');

                    var minDateMoment = moment(minDate, "YYYY-MM-DD");
                    var maxDateMoment = moment(maxDate, "YYYY-MM-DD");

                    var minDateMomentValidation = moment(minDate, "YYYY-MM-DD").add(-1, 'day');
                    var maxDateMomentValidation = moment(maxDate, "YYYY-MM-DD").add(1, 'day');

                    $purchaseDateInput.off('blur');
                    $purchaseDateInput.off('focus');
                    $purchaseDateInput.on('blur focus', function () {
                        var currentValue = $J(this).val();
                        if (currentValue) {
                            var currentValueMoment = moment(currentValue, 'DD/MM/YYYY');
                            var isValid = currentValueMoment.isValid();
                            var $errorMessageSpan = $J(this).closest('.field').find('.field-validation-valid');
                            var errorMessage = "Please enter a valid date(DD/MM/YYYY).";
                            if (isValid) {
                                errorMessage = 'Purchase date only valid from ' + minDateMoment.format('DD/MM/YYYY') + " until " + maxDateMoment.format('DD/MM/YYYY');
                                var withinRange = currentValueMoment.isBetween(minDateMomentValidation, maxDateMomentValidation);
                                if (withinRange) {
                                    $J(this).closest('.field').find('.field-validation-valid').text('');
                                    $J(this).removeClass('invalid');
                                }
                                else {
                                    if (!$J(this).hasClass('invalid')) {
                                        $J(this).addClass('invalid');
                                    }

                                    $errorMessageSpan.text(errorMessage);
                                }
                            }
                            else {
                                if (!$J(this).hasClass('invalid')) {
                                    $J(this).addClass('invalid');
                                }
                                $errorMessageSpan.text(errorMessage);
                            }
                        }
                    });

                    var isMaxDateFutureDate = moment().startOf('day').diff(maxDateMoment.startOf('day'), 'days') < 0;
                    if (isMaxDateFutureDate) {
                        maxDate = moment().format('YYYY-MM-DD');
                    }
                }

                if ($charityCashbackContainer.find('.charity-cb-step1-submit button').length > 0) {
                    $charityCashbackContainer.find('.charity-cb-step1-submit button').off('click');
                    $charityCashbackContainer.find('.charity-cb-step1-submit button').on('click', function (e) {
                        e.preventDefault();
                        var isValid = true;
                        var errorMessage = "This field is required.";
                        $charityCashbackContainer.find('.charity-cashback-step1-form').find("input").each(function () {
                            var $this = $J(this);
                            var isFldValid = $this[0].checkValidity();
                            if (!isFldValid) {
                                isValid = false;
                                if (!$this.hasClass('invalid')) {
                                    $this.addClass('invalid');
                                }
                                if ($(this).next().is(".field-validation-valid")) {
                                    $(this).next().text(errorMessage);
                                }
                                else if ($(this).attr("type") === "file") {
                                    $(this).closest(".file").next('.field-validation-valid').text(errorMessage);
                                }
                                else {
                                    $(this).siblings('.field-validation-valid').text(errorMessage);
                                }
                            }
                        });

                        $charityCashbackContainer.find('.charity-cashback-step1-form').find("select").each(function () {
                            var $errorMessageSpan = $J(this).closest('.field').find('.field-validation-valid');
                            if ($(this).attr("required") && $(this).prop("selectedIndex") < 1) {
                                if (!$J(this).hasClass('invalid')) {
                                    $J(this).addClass('invalid');
                                }
                                $errorMessageSpan.text(errorMessage);
                                isValid = false;
                            }
                        });


                        var form = $J($charityCashbackContainer).find('form');

                        if (isValid && $J(form)[0].checkValidity()) {
                            canonHelper.showSpinner();
                            var data = new FormData(form.get(0));
                            var token = canonHelper.getQueryString("token");
                            var gender = "";
                            if ($charityCashbackContainer.find("#gender-male:checked")) {
                                gender = $charityCashbackContainer.find("#gender-male:checked").val();
                            }
                            else if ($charityCashbackContainer.find("#gender-female:checked")) {
                                gender = $charityCashbackContainer.find("#gender-female:checked").val();
                            }

                            var receiptFile = {};
                            var isUploadReceipt = $charityCashbackContainer.find("#upload-receipt-yes:checked").length > 0;
                            var isSendReceiptViaEmail = !isUploadReceipt;
                            if (isUploadReceipt) {
                                data.append("ReceiptFile", form.find('#receipt')[0].files[0]);
                            }

                            var purchaseDate = $charityCashbackContainer.find('.cashback-date-bought').val();
                            var isPurchaseInStore = $charityCashbackContainer.find("#purchase-instore:checked").length > 0;
                            var isPurchaseOnline = !isPurchaseInStore;
                            var retailerName = isPurchaseOnline ? "Online" : $charityCashbackContainer.find('#retailer-name').val();
                            var isCharity = $J(this).attr("data-is-donate") === "true";

                            var firstName = $charityCashbackContainer.find('#firstname').val();
                            var lastName = $charityCashbackContainer.find('#lastname').val();
                            var emailAddress = $charityCashbackContainer.find('#email').val();
                            var contactNumber = $charityCashbackContainer.find('#contact-primary').val();
                            var stateOrRegion = $charityCashbackContainer.find('#address-state').val();
                            var postcode = $charityCashbackContainer.find('#address-postcode').val();


                            data.append("Token", token);
                            data.append("IsUploadReceipt", isUploadReceipt);

                            data.append("IsSendReceiptViaEmail", isSendReceiptViaEmail);
                            data.append("PurchaseDate", purchaseDate);
                            data.append("IsPurchaseInStore", isPurchaseInStore);
                            data.append("IsPurchaseOnline", isPurchaseOnline);
                            data.append("RetailerName", retailerName);
                            data.append("IsCharity", isCharity);
                            data.append("Gender", gender);
                            data.append("FirstName", firstName);
                            data.append("LastName", lastName);
                            data.append("EmailAddress", emailAddress);
                            data.append("ContactNumber", contactNumber);
                            data.append("StateOrRegion", stateOrRegion);
                            data.append("Postcode", postcode);
                            data = canonHelper.addAntiForgeryToken(data);
                            $.ajax({
                                type: 'POST',
                                url: '/cashback/charitycashbackform/step1cashbackdetails',
                                data: data,
                                contentType: false,
                                processData: false,
                                cache: false,
                                success: function (data) {
                                    if (data) {
                                        if (data.IsSuccessful != undefined && !data.IsSuccessful && data.ErrorMessage) {
                                            showGenericErrorModal();
                                        }
                                        else {
                                            $J($mainContainer).html(data).promise().done(function () {
                                                _cashBackScope.initCharityCashBack();
                                                navigateScreenToTop();
                                            });
                                        }
                                        canonHelper.hideSpinner();
                                    }
                                    else {
                                        canonHelper.hideSpinner();
                                        showGenericErrorModal();
                                    }
                                },
                                error: function () {
                                    canonHelper.hideSpinner();
                                    showGenericErrorModal();
                                }
                            });
                        }
                    });
                }

                //Step-2
                if ($charityCashbackContainer.find('.charity-cashback-step2-donate-form').length > 0) {

                    $charityCashbackContainer.find('.charity-cashback-step2-donate-form').submit(false);

                    $charityCashbackContainer.find(".field input[name*=charity]").off('change');
                    $charityCashbackContainer.find(".field input[name*=charity]").on('change', function () {
                        $charityCashbackContainer.find('.charity-cashback-donate-step2').removeAttr("disabled");
                        $charityCashbackContainer.find('.charity-cashback-donate-step2').addClass("valid");
                    });

                    var $selectedOrgInput = $charityCashbackContainer.find('.selectedCharityOrganisationId');
                    if ($selectedOrgInput.length > 0 && $selectedOrgInput.val()) {
                        $charityCashbackContainer.find(".field input[name*=charity]").each(function () {
                            if ($J(this).val() === $selectedOrgInput.val()) {
                                $J(this).prop('checked', true);
                            }
                        });
                    }

                    $charityCashbackContainer.find('.charity-cashback-donate-step2').off('click');
                    $charityCashbackContainer.find('.charity-cashback-donate-step2').on('click', function (e) {
                        e.preventDefault();
                        var selectedOrganisation = $J("div[class*=cashback-] div[class*=cashback-step] form .form-section .field input[name*=charity]:checked").val();
                        var token = canonHelper.getQueryString("token");

                        var postData = {
                            selectedOrganisation: selectedOrganisation,
                            token: token
                        };

                        if (selectedOrganisation) {
                            canonHelper.showSpinner();

                            var data = canonHelper.addAntiForgeryToken(postData);
                            var post = $.post('/cashback/charitycashbackform/step2selectcharityorganisation', data);

                            post.done(function (data) {
                                if (data) {
                                    if (data.IsSuccessful != undefined && !data.IsSuccessful && data.ErrorMessage) {
                                        showGenericErrorModal();
                                    }
                                    else {
                                        $J($mainContainer).html(data);
                                        _cashBackScope.initCharityCashBack();
                                    }

                                    canonHelper.hideSpinner();
                                }
                                else {
                                    canonHelper.hideSpinner();
                                    showGenericErrorModal();
                                }
                            });

                            post.fail(function () {
                                canonHelper.hideSpinner();
                                showGenericErrorModal();
                            });
                        }
                    });
                }

                if ($charityCashbackContainer.find('.charity-cashback-step2-form').length > 0) {
                    $charityCashbackContainer.find('.charity-cashback-step2-form').submit(false);
                    var $eftPaymentOption = $charityCashbackContainer.find("#payment-option-eft");
                    var $chequePaymentOption = $charityCashbackContainer.find("#payment-option-chq");
                    var $eftNZAccountNumber = $charityCashbackContainer.find(".EFTAccountNumbernz");
                    var $eftAccountNumber = $charityCashbackContainer.find("#EFTAccountNumber");
                    var $bankName = $charityCashbackContainer.find("#hdn_BankName");
                    var $bsbBankName = $charityCashbackContainer.find(".BSBBankName");
                    var $eftBsb = $charityCashbackContainer.find("#EFTBSB");
                    var $accountName = $charityCashbackContainer.find('#EFTAccountName');

                    if ($eftPaymentOption.length > 0) {
                        var $chequeSection = $charityCashbackContainer.find(".cheque-section");
                        var $eftSection = $charityCashbackContainer.find(".eft-section");
                        $chequeSection.hide();
                        $eftSection.hide();

                        $charityCashbackContainer.find("#payment-option-eft, #payment-option-chq").on('click', function () {
                            if ($J(this).attr('id').toLowerCase() === "payment-option-eft") {
                                $eftSection.show();

                                $eftSection.find("[mandatory]").attr("required", "true");

                                $chequeSection.hide();
                                $chequeSection.find("[mandatory]").removeAttr("required");
                                $chequeSection.find(".invalid").removeClass("invalid");

                                if ($eftNZAccountNumber.length > 0) {
                                    $eftNZAccountNumber.attr("pattern", "^[0-9]{2}-?[0-9]{4}-?[0-9]{7}-?[0-9]{2}$");
                                }

                                $eftPaymentOption.prop("checked", true);
                                $eftPaymentOption.attr("checked", "true");
                                $chequePaymentOption.prop("checked", false);
                                $chequePaymentOption.removeAttr("checked");

                                $charityCashbackContainer.find('#ChequeAddress').val('');
                                $charityCashbackContainer.find('#suburb').val('');
                                var validateField = $eftBsb.closest('.field').find('.field-validation-valid');
                                if (!validateField.hasClass("error")) {
                                    validateField.addClass("error");
                                }
                                if (validateField.hasClass("success")) {
                                    validateField.removeClass("success");
                                }
                                validateField.text("");
                            }
                            else {
                                $chequeSection.show();
                                $chequeSection.find("[mandatory]").attr("required", "true");

                                $eftSection.hide();
                                $eftSection.find("[mandatory]").removeAttr("required");
                                $eftSection.find(".invalid").removeClass("invalid");

                                $bankName.val('');

                                if ($("span[data-valmsg-for='EFTBSB']").html() !== '') {
                                    $("span[data-valmsg-for='EFTBSB']").html('');
                                }

                                if ($eftNZAccountNumber.length > 0) {
                                    $eftNZAccountNumber.removeAttr("pattern");
                                }

                                $eftPaymentOption.prop("checked", false);
                                $eftPaymentOption.removeAttr("checked");
                                $chequePaymentOption.prop("checked", true);
                                $chequePaymentOption.attr("checked", "true");

                                $accountName.val('');
                                $eftBsb.val('');
                                if ($eftNZAccountNumber.length > 0) {
                                    $eftNZAccountNumber.val('')
                                } else {
                                    $eftAccountNumber.val('');
                                }
                            }
                        });
                    }

                    if ($eftPaymentOption.prop("checked")) {
                        $eftPaymentOption.prop("checked", true).trigger("click");
                    }
                    else if ($chequePaymentOption.prop("checked")) {
                        $chequePaymentOption.prop("checked", true).trigger("click");
                    }

                    if ($eftNZAccountNumber.length > 0) {
                        MaskedInput({
                            elm: document.getElementById('EFTAccountNumber'), // select only by id
                            format: '__-____-_______-__',
                            separator: '-'
                        });
                    }

                    $bsbBankName.on("blur", function () {
                        var bsb = $eftBsb.val();
                        var currentForm = $J(this).closest('form');
                        $bankName.val('');
                        if ($("span[data-valmsg-for='EFTBSB']").html() != '')
                            $("span[data-valmsg-for='EFTBSB']").html('');
                        if (bsb && bsb.length > 0) {
                            canonHelper.showSpinner();
                            $J.ajax({
                                type: 'POST',
                                url: "/canonhub/cashbackform/getbankname?bsbCode=" + bsb,
                                contentType: 'application/json',
                                error: function (request, status, error) {
                                    canonHelper.hideSpinner();
                                    $eftBsb.addClass("invalid");
                                    _cashBackScope.cashBackHelper.onError(request, status, error, $J(currentForm));
                                }
                            }).done(function (response) {
                                var validateField = $eftBsb.closest('.field').find('.field-validation-valid');
                                if (response == '') {
                                    if (!validateField.hasClass("error")) {
                                        validateField.addClass("error");
                                    }
                                    if (validateField.hasClass("success")) {
                                        validateField.removeClass("success");
                                    }
                                    validateField.text("Invalid BSB");
                                    $eftBsb.addClass("invalid");
                                    if (!$charityCashbackContainer.find('.charity-cashback-step2').attr("disabled")) {
                                        $charityCashbackContainer.find('.charity-cashback-step2').attr("disabled", "disabled");
                                    }
                                }
                                else {
                                    if (validateField.hasClass("error")) {
                                        validateField.removeClass("error");
                                    }
                                    if (!validateField.hasClass("success")) {
                                        validateField.addClass("success");
                                    }
                                    validateField.text(response);
                                    $eftBsb.removeClass("invalid");
                                    $charityCashbackContainer.find('.charity-cashback-step2').removeAttr("disabled");
                                }
                                $eftBsb.show();
                                canonHelper.hideSpinner();

                            });
                        }
                    })

                    $charityCashbackContainer.find('.charity-cashback-step2-form').find("input").on('blur focus change keypress keyup', function () {
                        var $this = $J(this);
                        var isFldValid = $this[0].checkValidity() && $J('.BSBBankName.invalid').length === 0;
                        if (!isFldValid) {
                            if (!$charityCashbackContainer.find('.charity-cashback-step2').attr("disabled")) {
                                $charityCashbackContainer.find('.charity-cashback-step2').attr("disabled", "disabled");
                            }
                        }
                    });

                    $charityCashbackContainer.find('.charity-cashback-step2').off('click');
                    $charityCashbackContainer.find('.charity-cashback-step2').on('click', function (e) {
                        e.preventDefault();
                        if ($J(this).closest('form')[0].checkValidity() && $J('.BSBBankName.invalid').length === 0) {
                            var selectedOrganisation = $charityCashbackContainer.find(".field input[name*=charity]:checked").val();
                            var token = canonHelper.getQueryString("token");
                            var bankName = $eftNZAccountNumber.length > 0 ? '' : $bankName.val();
                            var bsbNumber = $eftNZAccountNumber.length > 0 ? '' : $eftBsb.val();
                            var accountNumber = $eftNZAccountNumber.length > 0 ? $eftNZAccountNumber.val() : $eftAccountNumber.val();
                            var accountName = $accountName.val();

                            var isBankTransfer = $eftPaymentOption.prop("checked");
                            var isGiftCard = !isBankTransfer;

                            var address = !isBankTransfer ? $charityCashbackContainer.find('#ChequeAddress').val() : '';
                            var cityOrSuburb = !isBankTransfer ? $charityCashbackContainer.find('#suburb').val() : '';
                            var stateOrRegion = !isBankTransfer ? $charityCashbackContainer.find('#address-state').val() : '';
                            var postcode = !isBankTransfer ? $charityCashbackContainer.find('#ChequePostcode').val() : '';

                            var postData = {
                                Token: token,
                                BankName: bankName,
                                BsbNumber: bsbNumber,
                                AccountNumber: accountNumber,
                                AccountName: accountName,
                                Address: address,
                                CityOrSuburb: cityOrSuburb,
                                StateOrRegion: stateOrRegion,
                                Postcode: postcode,
                                IsBankTransfer: isBankTransfer,
                                IsGiftCard: isGiftCard
                            };

                            canonHelper.showSpinner();

                            var data = canonHelper.addAntiForgeryToken(postData);
                            var post = $.post('/cashback/charitycashbackform/step2selectcashbackoption', data);

                            post.done(function (data) {
                                if (data) {
                                    if (data.IsSuccessful != undefined && !data.IsSuccessful && data.ErrorMessage) {
                                        showGenericErrorModal();
                                    }
                                    else {
                                        $J($mainContainer).html(data);
                                        _cashBackScope.initCharityCashBack();
                                    }

                                    canonHelper.hideSpinner();
                                }
                                else {
                                    canonHelper.hideSpinner();
                                    showGenericErrorModal();
                                }
                            });

                            post.fail(function () {
                                canonHelper.hideSpinner();
                                showGenericErrorModal();
                            });
                        }
                        else if (!$J(this).attr("disabled")) {
                            $J(this).attr("disabled", "disabled");
                        }
                    });
                }

                //Step-3
                if ($charityCashbackContainer.find('.charity-cashback-step3-container').length > 0) {
                    $charityCashbackContainer.find('.remodal-caller').on('click', function () {
                        var modelInst = $charityCashbackContainer.find('[data-remodal-id=' + $J(this).attr('data-remodal-target') + ']').remodal({ hashTracking: false });
                        modelInst.open();
                    });

                    $charityCashbackContainer.find('#AcceptTermsAndConditions').off('change');
                    $charityCashbackContainer.find('#AcceptTermsAndConditions').on('change', function () {
                        if ($J(this).prop('checked')) {
                            $charityCashbackContainer.find('.charity-cashback-step3').removeAttr('disabled');
                        }
                        else {
                            $charityCashbackContainer.find('.charity-cashback-step3').attr('disabled', 'true');
                        }
                    });

                    $charityCashbackContainer.find('.charity-cashback-step3-container').find('#AcceptedTermsAndConditions').off('click');
                    $charityCashbackContainer.find('.charity-cashback-step3-container').find('#AcceptedTermsAndConditions').on('click', function () {
                        var fl = true;
                        var $this = $J(this);
                        f1 = $this.prop('checked');
                        if (!fl) {
                            $this.next().next().text("This field is required.");
                        }
                        var button = $charityCashbackContainer.find(".charity-cashback-step3");
                        button.attr("disabled", "true");
                        button.removeClass("valid");
                        if (fl) {
                            button.removeAttr("disabled");
                            button.addClass("valid");
                        }
                    });
                }

                if ($charityCashbackContainer.find('.charity-cashback-step3').length > 0) {
                    $charityCashbackContainer.find('.charity-cashback-step3').off('click');
                    $charityCashbackContainer.find('.charity-cashback-step3').on('click', function (e) {
                        e.preventDefault();
                        var isValid = $charityCashbackContainer.find('#AcceptedTermsAndConditions:checked').length > 0;
                        if (isValid) {
                            var token = canonHelper.getQueryString("token");
                            var selectedOrganisation = '';
                            var postData = {
                                token: token
                            };
                            canonHelper.showSpinner();
                            var data = canonHelper.addAntiForgeryToken(postData);
                            var post = $.post('/cashback/charitycashbackform/step3reviewandsubmit', data);
                            post.done(function (data) {
                                if (data) {
                                    if (data.IsSuccessful != undefined && !data.IsSuccessful && data.Message) {
                                        showGenericErrorModal(data.Message);
                                    }
                                    else {
                                        $J($mainContainer).html(data);
                                        _cashBackScope.initCharityCashBack();
                                    }

                                    canonHelper.hideSpinner();
                                }
                                else {
                                    canonHelper.hideSpinner();
                                    showGenericErrorModal();
                                }
                            });
                            post.fail(function () {
                                canonHelper.hideSpinner();
                                showGenericErrorModal();
                            });
                        }
                    });
                }

                //Generic error message
                function showGenericErrorModal(message) {
                    var errorMessage = message ? message : "Sorry! We are experiencing technical difficulties, please contact our support team.";
                    $J('.global-error-message-body').html("<p>" + errorMessage + "</p>");
                    var modelInst = $('[data-remodal-id=globalErrorMessage]').remodal();
                    modelInst.open();
                }
            },

            initGiftRedemptionForm: function () {
                var $form = $J(".form-cash-back");
                var $giftOptionName = $form.find(".gift-option-name");
                if ($giftOptionName.length > 0) {
                    if ($J("input:radio[name='GiftName']:checked").length <= 0) {
                        $J(".gift-name-error").text("Please select a gift");
                    }
                    $J("input:radio[name='GiftName']").click(function () {
                        $J(".gift-name").text($J("input:radio[name='GiftName']:checked").val());
                    });
                }
            },

            initCompetitionRedemptionForm: function () {

                var that = this;
                var $form = $J(".form-cash-back");
                var $competitionOptionName = $form.find(".competition-option-name");
                if ($competitionOptionName.length > 0) {
                    if ($J("input:radio[name='CompetitionName']:checked").length <= 0) {
                        $J(".gift-name-error").text("Please select a Competition");
                    }
                    $J("input:radio[name='CompetitionName']").click(function () {
                        $J(".competition-name").text($J("input:radio[name='CompetitionName']:checked").val());

                        var CompetitionName = $J("input:radio[name='CompetitionName']:checked").val();

                        $J("#CompetitionNameToDisplay").val(CompetitionName);
                        that.updateCompetionmessage();
                    });
                }

                if ($("#competition-cashback-Product-name").length > 0) {
                    $J("#competition-cashback-Product-name").change(function () {
                        that.hideShowCompetitionField();
                    });
                }

                that.hideShowCompetitionField();


            },

            updateCompetionmessage: function () {
                var selectedItem = $J("#competition-cashback-Product-name option:selected");
                if (selectedItem.val() !== "") {
                    var cashbackValue = selectedItem.data("singlecashback-value");

                    var competiotionName = $J("#CompetitionNameToDisplay").val();
                    var competitionMessage = selectedItem.data("competition-message");

                    cashbackValue = !cashbackValue ? '' : cashbackValue;
                    competiotionName = !competiotionName ? '' : competiotionName;

                    if (competitionMessage != undefined) {
                        competitionMessage = competitionMessage.replace("{cashback_amount}", cashbackValue);
                        competitionMessage = competitionMessage.replace("{competition_name}", competiotionName);

                    }

                    $J("#cashback-competition-message").html(competitionMessage);


                }

            },

            hideShowCompetitionField: function () {

                var that = this;
                var selectedItem = $J("#competition-cashback-Product-name option:selected");
                if (selectedItem.length > 0) {

                    if (selectedItem.val() !== "") {
                        var cashbackValue = selectedItem.data("singlecashback-value");
                        var cashbackCompetition = $J(".cashback-competition-show-hide");
                        var competitionOnly = $J(".competition-show-hide");
                        if (cashbackValue > 0) {
                            cashbackCompetition.show();
                            cashbackCompetition.find("[mandatory]").attr("required", "true");

                            competitionOnly.find("[mandatory]").removeAttr("required");
                            competitionOnly.hide();
                            $J("#UseCompetitionPaymentOption").val(false);
                        }
                        else {
                            cashbackCompetition.find("[mandatory]").removeAttr("required");
                            cashbackCompetition.hide();

                            competitionOnly.show();
                            competitionOnly.find("[mandatory]").attr("required", "true");


                            $J("#UseCompetitionPaymentOption").val(true);
                        }
                        $J("#SingleCashBackValue").val(cashbackValue);
                        $J(".cashback-amt").html("$" + cashbackValue);
                        $J("#CashbackAmount").val(cashbackValue);
                        $J("#ProductId").val(selectedItem.data("product-tile-id"));

                        that.updateCompetionmessage();

                    }
                    else {
                        $J("#SingleCashBackValue").val(0);
                        $J(".cashback-amt").html("$" + 0);
                        $J("#CashbackAmount").val(0);
                        $J("#ProductId").val(selectedItem.data("product-tile-id"));
                        $J(".cashback-competition-show-hide").hide();
                        $J(".competition-show-hide").hide();
                    }
                }


            },


            initCashbackProductFeedFilter: function () {

                //Product Filter Type
                $J('.cashback-category-filter select').change(function () {
                    var selectedFilterType = '';

                    $(this).find('option:selected').each(function () {
                        selectedFilterType = $(this).val();
                        $J(this).removeAttr('selected');
                    });

                    $J(this).val(selectedFilterType);

                    if (selectedFilterType === 'all') {
                        selectedFilterType = '';
                    }

                    var container = $J(this).closest('.cashback-container');
                    container.find(".cashback-subcategory-filter li").each(function () {
                        if (!$J(this).hasClass("hide--me") && !$J(this).hasClass("all")) {
                            $J(this).addClass("hide--me");
                        }
                        if ($J(this).hasClass("all") && !$J(this).hasClass('active')) {
                            $J(this).addClass('active');
                        }
                        if ($J(this).attr('data-filter-type') === selectedFilterType) {
                            $J(this).removeClass("hide--me");
                        }
                        if ($J(this).hasClass("all")) {
                            $J(this).attr('data-filter-type', selectedFilterType);
                            $J(this).trigger('click');
                        }
                    });

                    var subcategoryContainer = container.find(".tabs");
                    if (subcategoryContainer) {

                        var hideTopSearchBar;

                        var topSearchBar = container.find('.filter-container .search-container');
                        var numberOfSubcategories = container.find(".cashback-subcategory-filter li[data-filter-type='" + selectedFilterType + "']").length;
                        if (numberOfSubcategories > 1) {
                            $(subcategoryContainer).removeClass('hide--me');
                            hideTopSearchBar = true;
                        }
                        else {
                            hideTopSearchBar = false;
                            if (!$(subcategoryContainer).hasClass('hide--me'))
                                $(subcategoryContainer).addClass('hide--me');
                        }

                        if (hideTopSearchBar) {
                            if (!$(topSearchBar).hasClass('hide--me')) {
                                $(topSearchBar).addClass('hide--me');
                            }
                        }
                        else {
                            $(topSearchBar).removeClass('hide--me');
                        }
                    }
                });

                //List of product Filter by, on desktop
                $J(".cashback-subcategory-filter li:not(.heading)").on('click', function () {
                    var tileContainer = $J(this).closest('.cashback-container').find('.tile-container');
                    var sourceId = $J(tileContainer).attr('data-source');

                    var filterContainer = $J(this).closest('.cashback-container');
                    var searchInput = $J(filterContainer).find('.cashback-feed-keyword');
                    if (searchInput && searchInput.length > 0 && searchInput.attr('data-keyword')) {
                        searchInput.attr('data-keyword', '');
                        searchInput.val('');
                    }

                    var postData = {
                        CurrentCampaignPageId: sourceId,
                        PageIndex: 0,
                        SelectedCategory: $J(this).attr('data-filter-type'),
                        SelectedSubcategory: $J(this).attr('data-filter'),
                        Keyword: ''
                    };

                    $J(this).parent('ul').find('li').each(function () {
                        $J(this).removeClass("active");
                    });

                    $J(this).addClass("active");

                    var filterText = '';
                    if ($J(this).hasClass('all')) {
                        var selectedCategoryFilter = $J(this).closest('.cashback-container').find('.filter-container select option:selected').val();
                        if (selectedCategoryFilter === 'all') {
                            filterText = 'total';
                        }
                        else {
                            filterText = $J(this).closest('.cashback-container').find('select option:selected').text();
                        }
                    }
                    else {
                        filterText = $J(this).text();
                    }

                    var subcategoryContainer = filterContainer.find('.tabs');
                    var topSearchBar = subcategoryContainer.find('.filter-container .search-container');
                    if (subcategoryContainer) {
                        if (subcategoryContainer.hasClass('hide--me')) {
                            $(topSearchBar).removeClass('hide--me');
                        }
                        else {
                            if (!$(topSearchBar).hasClass('hide--me')) {
                                $(topSearchBar).addClass('hide--me');
                            }
                        }
                    }

                    _cashBackScope.getCashbackProductFeed(postData, tileContainer, false, true, filterText);

                });
            },

            initCashbackProductFeedLoadMore: function () {
                $J('.cashback-load-more-feed a').on('click', function (e) {
                    e.preventDefault();

                    var filterContainer = $J(this).closest('.cashback-container');
                    var container = $J(filterContainer).find('.cashback-subcategory-filter');
                    var searchInput = $J(filterContainer).find('.cashback-feed-keyword');
                    var keyword = searchInput && searchInput.length > 0 && searchInput.attr('data-keyword') ? searchInput.attr('data-keyword') : '';

                    var selectedFilter = '';
                    var selectedFilterType = '';

                    var selectedSubcategoryFilterElement = $J(container).find('li.active');
                    if (selectedSubcategoryFilterElement) {
                        selectedFilter = $J(selectedSubcategoryFilterElement).attr('data-filter');
                        selectedFilterType = $J(selectedSubcategoryFilterElement).attr('data-filter-type');
                    }

                    if (selectedFilter === 'all') {
                        selectedFilter = '';
                    }

                    if (selectedFilterType === 'all') {
                        selectedFilterType = '';
                    }

                    var tileContainer = $J(this).closest('.cashback-container').find('.tile-container');
                    var sourceId = $J(tileContainer).attr('data-source');

                    var currentPageIndex = $J(this).attr("data-current-page");
                    var pageToRender = parseInt(currentPageIndex) + 1;

                    var postData = {
                        CurrentCampaignPageId: sourceId,
                        PageIndex: pageToRender,
                        SelectedCategory: selectedFilterType,
                        SelectedSubcategory: selectedFilter,
                        Keyword: keyword
                    };

                    $J(this).blur();
                    _cashBackScope.getCashbackProductFeed(postData, tileContainer, true, false);
                });
            },

            initCashbackProductFeedByKeyword: function () {
                $J('.cashback-feed-keyword').keypress(function (e) {
                    if (e.which === 13) {
                        var keyword = $J(this).val();
                        var currentKeyword = $J(this).attr('data-keyword');
                        if (currentKeyword == undefined || currentKeyword !== keyword) {
                            searchByKeyword(keyword, $J(this));
                            $J(this).attr('data-keyword', keyword);
                        }
                    }
                });

                function searchByKeyword(keyword, el) {

                    var filterContainer = $J(el).closest('.cashback-container');
                    var tileContainer = filterContainer.find(".tile-container");
                    var sourceId = $J(tileContainer).attr('data-source');

                    filterContainer.find('.cashback-category-filter select option:selected').removeAttr('selected');
                    var firstCategoryOption = filterContainer.find('.cashback-category-filter select option:first');
                    if (firstCategoryOption && !firstCategoryOption.attr('selected')) {
                        firstCategoryOption.attr('selected', '');
                    }

                    var subcategoryContainer = filterContainer.find(".tabs");
                    if (!$(subcategoryContainer).hasClass('hide--me')) {
                        $(subcategoryContainer).addClass('hide--me');
                    }

                    var topSearchBar = filterContainer.find('.filter-container .search-container');
                    if (topSearchBar) {
                        $(topSearchBar).removeClass('hide--me');
                        $(topSearchBar).find('input').attr('data-keyword', keyword);
                        $(topSearchBar).find('input').val(keyword);

                        $(subcategoryContainer).find('.cashback-feed-keyword').attr('data-keyword', keyword);
                        $(subcategoryContainer).find('.cashback-feed-keyword').val(keyword);
                    }

                    var firstSubcategoryOption = filterContainer.find('.cashback-subcategory-filter li:first');

                    filterContainer.find('.cashback-subcategory-filter li.active').each(function () {
                        $(this).removeClass('active');
                    });

                    if (firstSubcategoryOption && !$(firstSubcategoryOption).hasClass('active')) {
                        $(firstSubcategoryOption).addClass('active');
                    }

                    var subCategory = filterContainer.find('.cashback-subcategory-filter li.active');

                    var filterText = '';
                    if ($J(subCategory).hasClass('all')) {
                        var selectedCategory = $J(filterContainer).find('.filter-container select option:selected').val();
                        if (selectedCategory === 'all') {
                            filterText = 'total';
                        }
                        else {
                            filterText = $J(filterContainer).find('select option:selected').text();
                        }
                    }
                    else {
                        filterText = $J(subCategory).text();
                    }

                    var postData = {
                        CurrentCampaignPageId: sourceId,
                        PageIndex: 0,
                        SelectedCategory: '',
                        SelectedSubcategory: '',
                        Keyword: keyword
                    };

                    _cashBackScope.getCashbackProductFeed(postData, tileContainer, false, true, filterText, true);
                }
            },

            getCashbackProductFeed: function (postData, tileContainer, isLoadMore, updateCounter, filterText, isSearchByKeyword) {
                canonHelper.showSpinner();
                var data = canonHelper.addAntiForgeryToken(postData);
                var post = $J.post('/content-tile/campaign/getcashbackproducts', data);

                post.done(function (data) {
                    var template = $J("#cashback-product-template").html();
                    var loadMoreEl = $J(tileContainer).closest('.cashback-feed').find(".cashback-load-more-feed a");
                    var loadMoreContainerEl = $J(loadMoreEl).parent();

                    if (data.SkinnyCashbackTiles) {
                        var result = Mustache.to_html(template, data);
                        if (isLoadMore) {
                            $J(tileContainer).append(result);
                        } else {
                            $J(tileContainer).html(result);
                        }
                        canonHelper.tileMarginFix($J(tileContainer));
                    }

                    if (updateCounter) {
                        var counterText = $J(tileContainer).closest('.cashback-feed').find('.total-products-count');
                        if (counterText.length > 0) {
                            counterText.text("There " + (parseInt(data.TotalItemFound) > 1 ? "are" : "is") + " " + data.TotalItemFound + " " + (parseInt(data.TotalItemFound) > 1 ? "items" : "item") + " in this list.");
                        }
                    }

                    if (data && data.IsNextPageAvailable) {
                        var loadMoreText = "<span>Load more " + data.TilesTypeForLoadMore + "</span><br>" + "(" + data.NextItemToDisplayed + ") " + data.TilesCounterForLoadMore + " left";
                        $J(loadMoreEl).html(loadMoreText);
                        $J(loadMoreEl).attr("data-current-page", data.CurrentPageIndex);
                        $J(loadMoreContainerEl).removeClass('hide--me');
                    } else {
                        if (!loadMoreContainerEl.hasClass('hide--me')) {
                            loadMoreContainerEl.addClass('hide--me');
                        }
                    }

                    _cashBackScope.initHatch();

                    canonHelper.hideSpinner();

                });

                post.fail(function () {
                    canonHelper.hideSpinner();
                });

                post.always(function () {
                    //$J('.load-more-feed button').prop('disabled', false).removeClass('loading');
                });
            },

            initHatch: function() {
                var responseData = $J.getJSON("/api/api/getpardotcookie");
                responseData.done(function (data) {
                    if (data != undefined && data.value != undefined && $.trim(data.value) !== "") {

                        var currentData = $J('.hatch-button').parent().attr("data-extra-request-parameters");
                        if (currentData === undefined) {
                            return;
                        }
                        var newData = currentData.replace("'uid': 'undefined'", "'uid': '" + data.value + "'");

                        $J('.hatch-button').parent().attr("data-extra-request-parameters", newData);

                        HatchRequest.init();
                    }
                });

                HatchRequest.init();

                $(".hatch-button").on('click', function () {
                    setTimeout(function () {
                        if ($("[class^='hatch-widget'][role='presentation']").length > 1) {
                            $("[class^='hatch-widget'][role='presentation'][aria-hidden='true'] button[aria-label='close']").trigger('click');
                        }
                    }, 10);
                });
            },

            initCashBackTilesHatch: function() {
                $J(window).load(function () {
                    setTimeout(function () {
                        _cashBackScope.initHatch();
                    }, 2500);
                });
            }
        };

        return _cashBackScope;

    })();

    $J(document).ready(function () {
        if (canonHelper !== undefined) {
            cashBack.init();
        }
    });
})(jQuery);;
(function ($J) {
    var eventBooking = (function () {
        var _eventBookingScope = {
            init: function () {
                this.initEventBooking();
            },

            navigateScreenToTop: function () {
                $('html, body').animate({
                    scrollTop: $(".event-booking-steps") - $("header").height()
                }, 1000);
            },

            navigateToPageOnUnsuccessful: function (data) {
                if (data != undefined && data && data.Succeed != undefined) {
                    if (!data.Succeed && data.RedirectUrl != undefined && data.RedirectUrl) {
                        document.location = data.RedirectUrl;
                    }
                    else {
                        console.log('need html to display a message here');
                    }
                }
            },

            updateEventTrakerField: function (container) {
                if (container.length > 0) {
                    var trakerField = $J(".event-booking-transaction-info");
                    if (trakerField.length > 0) {
                        trakerField.attr("data-eventname", container.data("eventname"));
                        trakerField.attr("data-eventtype", container.data("eventtype"));
                        trakerField.attr("data-ismycanon", container.data("ismycanon"));
                        trakerField.attr("data-currentstep", container.data("currentstep"));
                        trakerField.val(container.data("eventname") + " - " + container.data("currentstep"));
                    }
                }
            },

            validateBookingForm: function (currentForm) {
                var isValid = true;
                if (currentForm.length > 0) {
                    var errorMessage = "This field is required.";
                    currentForm.find("input select").each(function () {
                        var $this = $J(this);
                        var isFldValid = $this[0].checkValidity();
                        if ($this.prop("type") == "email") {
                            errorMessage = "Please enter a valid email.";
                        }
                        if (!isFldValid) {
                            isValid = false;
                            if (!$this.hasClass('invalid')) {
                                $this.addClass('invalid');
                            }
                            if ($(this).next().is(".field-validation-valid")) {
                                $(this).next().text(errorMessage);
                            }
                            else {
                                $(this).siblings('span').text(errorMessage);
                            }
                        }
                    });
                }

                return isValid;
            },

            hideOrShowStep: function (container, currentStep) {
                $J(container).find(".wrapper-border").not("[data-active='1']").hide();
                $J(container).find(".wrapper-border[data-active='0'][data-currentstep='" + currentStep + "']").remove();
            },

            updateEventOrderDetails: function (bookingStepsContainer, currentStep) {
                canonHelper.showSpinner();
                var container = $J(bookingStepsContainer).find(".event-order-review-details");
                var key = $J(".event-key").val();
                var postData = {
                    key: key
                };

                var data = canonHelper.addAntiForgeryToken(postData);
                var post = $.post("/booking-steps/eventbooking/updateeventorderdetails", data);

                post.done(function (data) {
                    _eventBookingScope.navigateToPageOnUnsuccessful(data);
                    if (data) {
                        $J(container).html(data);
                        _eventBookingScope.initEventBooking();
                        if ($(".event-key").attr("data-pm")) {
                            $(".review-payment-method").html($(".event-key").attr("data-pm"));
                            $(".review-payment-method").closest(".payment-method").removeClass("hide--me");
                        }
                    }
                    canonHelper.hideSpinner();
                });

                post.fail(function () {
                    canonHelper.hideSpinner();
                });
            },

            constructFieldValidation: function () {
                var bookingForms = $J('.event-booking-steps form');
                bookingForms.each(function () {
                    var currentForm = $J(this);
                    var submitButton = currentForm.find(".form-submit a, .form-submit button");
                    if (!currentForm.hasClass("event-booking-mycanon-login")) {
                        currentForm.submit(false);
                    }
                    if (currentForm[0].checkValidity()) {
                        submitButton.removeAttr("disabled");
                        if (!submitButton.hasClass("valid")) {
                            submitButton.addClass("valid");
                        }
                    }
                    currentForm.find('input, select').on('blur focus change keypress keyup', function () {
                        var errorMessage = "This field is required.";
                        var $this = $J(this);
                        var isFldValid = $this[0].checkValidity();
                        var isFormValid = currentForm[0].checkValidity();
                        if ($this.prop("type") == "email") {
                            errorMessage = "Please enter a valid email.";
                        }
                        $this.removeClass('invalid');
                        if ($(this).next().is(".field-validation-valid")) {
                            $(this).next().text("");
                        }
                        if (!isFldValid) {
                            if (!$this.hasClass('invalid')) {
                                $this.addClass('invalid');
                            }
                            if ($(this).next().is(".field-validation-valid")) {
                                $(this).next().text(errorMessage);
                            }
                            else {
                                $(this).siblings('span').text(errorMessage);
                            }
                        }
                        if (isFormValid) {
                            submitButton.removeAttr("disabled");
                            if (!submitButton.hasClass("valid")) {
                                submitButton.addClass("valid");
                            }
                        }
                        else {
                            if (!submitButton.attr("disabled")) {
                                submitButton.attr("disabled", "");
                            }
                            submitButton.removeClass("valid");
                        }
                    });
                });
            },

            makeElementAsReadyOnly: function (element) {
                $J(element).attr("disabled", "disabled");
            },

            showPaymentScreen: function (bookingContainer, goBackbutton) {
                var currentStep = $J(bookingContainer).data("currentstep") - 1;
                var hasPaymentDetails = false;

                var trakerField = $J(".event-booking-transaction-info");
                if (trakerField.length > 0) {
                    trakerField.attr("data-currentstep", currentstep);
                    trakerField.val(trakerField.attr("data-eventname") + " - " + currentstep);
                }

                $J(bookingContainer).data("currentstep", currentStep);
                $J(".paymentReview").addClass("hide--me");
                $J(".pay-confirm-section").addClass("hide--me");
                $J(".section-tabs").removeClass("hide--me");
                $J(".payment-view").find("h2").removeClass("hide--me");
                $J(".payment-section").removeClass("hide--me");
                $J(".paymentReview .event-order-details").css("border-bottom", "1px #d7d7d7 solid;");
                $J(".payment-view .event-order-details").css("border-top", "1px #d7d7d7 solid;");
                $J(".payment-view .event-order-details").css("border-bottom", "1px #d7d7d7 solid;");
                $J(".pay-confirm-section").css("padding", "0rem 0rem 0rem");
                $J(goBackbutton).addClass("event-booking-back-button");
                $J(goBackbutton).removeClass("event-booking-Payment-Review-back-button");
                $J("#acceptpaymentcondition").removeAttr("required");
                $J(".form-payment-gateway input,select").each(function (e) {
                    if ($(this).val() != '') {
                        hasPaymentDetails = true;
                    }
                });
                $J(".edit-payment-btn-container").addClass("hide--me")
                if (hasPaymentDetails) {
                    _eventBookingScope.makeElementAsReadyOnly($J(".payment-section input,select"));
                    $J(".edit-payment-btn-container").removeClass("hide--me")
                }
            },

            renderEventBookingStep3: function (bookingStepsContainer, data) {
                _eventBookingScope.navigateToPageOnUnsuccessful(data);
                if (data) {
                    $J(bookingStepsContainer).html(data).promise().done(function () {
                        _eventBookingScope.initEventBooking();
                        if (data.search("event-booking-payment-container") > -1) {
                            canonHelper.getScript("/js/payment.js").done(function (data) { }).fail(function () { });
                        }
                        _eventBookingScope.navigateScreenToTop();
                        _eventBookingScope.updateEventTrakerField(bookingStepsContainer.find(".wrapper-border"));
                    });
                }
                else {
                    //TODO: Show message or html required
                    console.log('need html to display a message here');
                }
            },

            initOnBackButtonClick: function () {
                var $eventBookingBackButton = $J('.event-booking-back-button');
                if ($eventBookingBackButton.length > 0) {
                    $J($eventBookingBackButton).off('click');
                    $J($eventBookingBackButton).on('click', function (e) {
                        e.preventDefault();
                        if ($J(this).hasClass("event-booking-Payment-Review-back-button")) {
                            var bookingContainer = $J(this).closest(".event-booking-steps").find(".wrapper-border");
                            _eventBookingScope.showPaymentScreen(bookingContainer, $J(this));
                            if ($J(".form-payment-gateway").length > 0 && $J(".form-payment-gateway")[0].checkValidity()) {
                                $J(".payment-review-btn").removeAttr("disabled");
                                $J(".payment-review-btn").addClass("valid");
                            }
                            _eventBookingScope.initEventBooking();
                        }
                        else {
                            canonHelper.showSpinner();
                            var bookingStepsContainer = $J(this).closest(".event-booking-steps");
                            var key = $J(".event-key").val();
                            var postData = {
                                key: key
                            };
                            var data = canonHelper.addAntiForgeryToken(postData);
                            var post = $.post("/booking-steps/eventbooking/goback", data);
                            post.done(function (data) {
                                _eventBookingScope.navigateToPageOnUnsuccessful(data);
                                if (data) {
                                    $J(bookingStepsContainer).html(data).promise().done(function () {
                                        _eventBookingScope.initEventBooking();

                                        if ($J('.event-booking-login-form').length > 0) {
                                            $J('.event-booking-login-form').each(function () {
                                                var currentForm = $J(this);
                                                var button = currentForm.find(".event-booking-step3");
                                                if (currentForm[0].checkValidity()) {
                                                    button.removeAttr("disabled");
                                                    button.addClass("valid");
                                                }
                                            });
                                        }

                                        _eventBookingScope.navigateScreenToTop();
                                        _eventBookingScope.updateEventTrakerField(bookingStepsContainer.find(".wrapper-border"));
                                    });
                                }
                                canonHelper.hideSpinner();
                            });
                            post.fail(function () {
                                canonHelper.hideSpinner();
                            });
                        }
                    });
                }

                if ($J('.event-booking-Payment-Review-back-button').length > 0) {
                    $J('.event-booking-Payment-Review-back-button').off('click');
                    $J('.event-booking-Payment-Review-back-button').on('click', function (e) {
                        e.preventDefault();
                        var bookingContainer = $J(this).closest(".event-booking-steps").find(".wrapper-border");
                        _eventBookingScope.showPaymentScreen(bookingContainer, $J(this));
                        _eventBookingScope.initEventBooking();
                    });
                }
            },

            initStep1EventBooking: function () {
                if ($J('.event-session-cta').length > 0) {
                    $J('.event-session-cta').off('click');
                    $J('.event-session-cta').on('click', function (e) {
                        e.preventDefault();
                        canonHelper.showSpinner();
                        var bookingStepsContainer = $J(this).closest('.event-booking-steps');
                        var key = $J('.event-key').val();
                        var tickets = $J(bookingStepsContainer).find('.select-ticket-number').val();
                        var sessionId = $J(this).closest('.event-session-item').attr('data-session-id');

                        var postData = {
                            SessionId: sessionId,
                            Tickets: tickets,
                            Key: key
                        };

                        var data = canonHelper.addAntiForgeryToken(postData);
                        var post = $.post('/booking-steps/eventbooking/step1availability', data);

                        post.done(function (data) {
                            if (data.Succeed) {
                                document.location = document.location.origin + document.location.pathname + "?key=" + key;
                            }
                            else {
                                //TODO: Show message or html required
                                console.log('need html to display a message here');
                                canonHelper.hideSpinner();
                            }
                        });

                        post.fail(function () {
                            canonHelper.hideSpinner();
                        });
                    });
                }
            },

            initStep2EventBooking: function () {
                if ($J('.event-booking-submit').length > 0) {
                    $J('.event-booking-submit').off('click');
                    $J('.event-booking-submit').on('click', function (e) {
                        e.preventDefault();
                        canonHelper.showSpinner();
                        var bookingStepsContainer = $J(this).closest('.event-booking-steps');
                        var orderDetailsForm = $J(bookingStepsContainer).find(".event-booking-step3-form");
                        if (_eventBookingScope.validateBookingForm($J(orderDetailsForm))) {
                            var key = $J('.event-key').val();
                            var firstname = $J(orderDetailsForm).find('#firstname').val();
                            var lastname = $J(orderDetailsForm).find('#lastname').val();
                            var email = $J(orderDetailsForm).find('#email').val();
                            var contactNumber = $J(orderDetailsForm).find('#contact-primary').val();

                            var postData = {
                                key: key,
                                firstname: firstname,
                                lastname: lastname,
                                email: email,
                                primaryContactNumber: contactNumber
                            };

                            var data = canonHelper.addAntiForgeryToken(postData);
                            var post = $.post('/booking-steps/eventbooking/step2orderdetails', data);

                            post.done(function (data) {
                                _eventBookingScope.renderEventBookingStep3(bookingStepsContainer, data);
                                canonHelper.hideSpinner();
                            });

                            post.fail(function () {
                                canonHelper.hideSpinner();
                            });
                        }
                        else {
                            canonHelper.hideSpinner();
                        }
                    });
                }

                if ($J('.event-booking-mycanon-login-submit').length > 0) {
                    $J('.event-booking-mycanon-login-submit').off('click');
                    $J('.event-booking-mycanon-login-submit').on('click', function (e) {
                        var currentForm = $J(this).closest('.event-booking-mycanon-login');
                        e.preventDefault();
                        if (_eventBookingScope.validateBookingForm($J(currentForm))) {
                            currentForm.submit();
                        }
                    });
                }
            },

            initStep3EventBooking: function () {
                if ($J('.form-free-event-confirmation').length > 0) {
                    $J('.form-free-event-confirmation').find('input, select').on('blur focus change', function (e) {
                        var fl = true;
                        var $this = $J(this);
                        if ($this.attr('id') === "acceptfeeeventcondition") {
                            fl = $this[0].checkValidity();
                            if (!fl) {
                                $this.next().next().text("This field is required.");
                            }
                            else {
                                $this.next().next().text("");
                                var response = grecaptcha.getResponse(captchaWidgetId);
                                if (response.length <= 0) {
                                    fl = false;
                                }
                            }
                        }
                        else {
                            fl = $this.valid() && $this[0].checkValidity();
                        }
                        var currentForm = $this.closest(".form-free-event-confirmation");
                        var button = currentForm.find(".free-event-confirmation");
                        button.attr("disabled", "true");
                        button.removeClass("valid");
                        if (fl && currentForm[0].checkValidity()) {
                            button.removeAttr("disabled");
                            button.addClass("valid");
                        }
                    });
                }
                if ($J('.free-event-confirmation').length > 0) {
                    $J('.free-event-confirmation').off('click');
                    $J('.free-event-confirmation').on('click', function (e) {
                        e.preventDefault();
                        var bookingStepsContainer = $J(this).closest('.event-booking-steps');
                        var orderDetailsForm = $J(bookingStepsContainer).find(".form-free-event-confirmation");
                        if (_eventBookingScope.validateBookingForm($J(orderDetailsForm))) {
                            canonHelper.showSpinner();

                            var subscriptionType = -1;

                            if ($J('input[name="eventSubscriptionTypeId"]:checked').length > 0) {
                                subscriptionType = $J("#eventSubscriptionTypeId").val();
                            }

                            var key = $J('.event-key').val();
                            var postData = {
                                key: key,
                                subscriptionTypeId: subscriptionType
                            };

                            var data = canonHelper.addAntiForgeryToken(postData);
                            var post = $.post('/booking-steps/eventbooking/step3orderdetailsconfirmation', data);

                            post.done(function (data) {
                                _eventBookingScope.navigateToPageOnUnsuccessful(data);
                                if (data) {
                                    $J(bookingStepsContainer).html(data);
                                    _eventBookingScope.initEventBooking();
                                    _eventBookingScope.navigateScreenToTop();
                                    _eventBookingScope.updateEventTrakerField(bookingStepsContainer.find(".wrapper-border"));
                                }
                                else {
                                    //TODO: Show message or html required
                                    console.log('need html to display a message here');
                                }

                                canonHelper.hideSpinner();
                            });

                            post.fail(function () {
                                canonHelper.hideSpinner();
                            });
                        }
                    });
                }
            },

            initStep4EventBooking: function () {
                if ($J('.edit-event-booking').length > 0) {
                    $J('.edit-event-booking').off('click');
                    $J('.edit-event-booking').on('click', function (e) {
                        e.preventDefault();
                        canonHelper.showSpinner();
                        var bookingStepsContainer = $J(this).closest('.event-booking-steps');

                        var key = $J('.event-key').val();
                        var postData = {
                            key: key
                        };

                        var eventType = $J(this).data("eventtype");
                        var data = canonHelper.addAntiForgeryToken(postData);
                        var post = $.post('/booking-steps/eventbooking/editeventbooking', data);

                        post.done(function (data) {
                            _eventBookingScope.navigateToPageOnUnsuccessful(data);
                            if (data) {
                                if (eventType === "paid") {
                                    $J(bookingStepsContainer).find(".wrapper-border").attr("data-active", "0");
                                    $J(bookingStepsContainer).append(data).promise().done(function () {
                                        _eventBookingScope.initEventBooking();
                                        _eventBookingScope.navigateScreenToTop();
                                        var bookingContainer = $J(bookingStepsContainer).find(".wrapper-border[data-active='1']");
                                        _eventBookingScope.updateEventTrakerField(bookingContainer);
                                        var currentStep = bookingContainer.data("currentstep");
                                        _eventBookingScope.hideOrShowStep(bookingStepsContainer, currentStep);
                                        $J(bookingStepsContainer).find(".booking-steps").addClass("hide--me");
                                    });
                                }
                                else {
                                    $J(bookingStepsContainer).html(data);
                                    _eventBookingScope.initEventBooking();
                                    _eventBookingScope.navigateScreenToTop();
                                    _eventBookingScope.updateEventTrakerField(bookingStepsContainer.find(".wrapper-border"));
                                }
                            }
                            else {
                                //TODO: Show message or html required
                                console.log('need html to display a message here');
                            }

                            canonHelper.hideSpinner();
                        });

                        post.fail(function () {
                            canonHelper.hideSpinner();
                        });
                    });
                }
            },

            initEventBooking: function () {

                var removeReadyOnlyForElement = function () {
                    $J(element).removeAttr("disabled");
                };

                _eventBookingScope.constructFieldValidation();
                _eventBookingScope.initOnBackButtonClick();
                _eventBookingScope.initStep1EventBooking();
                _eventBookingScope.initStep2EventBooking();
                _eventBookingScope.initStep3EventBooking();
                _eventBookingScope.initStep4EventBooking();

                /*Toggle Sign-up on Step-5*/
                if ($J('.event-toggle-signup').length > 0) {
                    $J('.event-toggle-signup').off('click');
                    $J('.event-toggle-signup').on('click', function (e) {
                        e.preventDefault();
                        $J('.event-booking-signup-form').toggleClass('hide--me');
                        $J(this).toggleClass('hide--me');
                    });
                }

                /*Sign-up action*/
                if ($J('.event-booking-signup').length > 0) {
                    $J('.event-booking-signup').off('click');
                    $J('.event-booking-signup').on('click', function (e) {
                        e.preventDefault();
                        var form = $J('.event-booking-signup-form');
                        if (form.valid()) {
                            canonHelper.showSpinner();

                            var firstname = $J('.firstname-event-booking').val();
                            var lastname = $J('.lastname-event-booking').val();
                            var email = $J('.email-event-booking').val();
                            var password = $J('.password-event-booking').val();
                            var acceptedtosubscribe = $('#AcceptedToSubscribe').is(':checked');
                            var postData = {
                                firstname: firstname,
                                lastname: lastname,
                                email: email,
                                password: password,
                                acceptedtosubscribe: acceptedtosubscribe
                            };

                            var data = canonHelper.addAntiForgeryToken(postData);
                            var post = $.post('/booking-steps/eventbooking/registermycanon', data);

                            post.done(function (data) {
                                if (data.IsSuccessful) {
                                    $J('.event-booking-signup-form').toggleClass('hide--me');
                                    $J('.event-booking-signup-container').toggleClass('hide--me');
                                    $J('.registration-succeeded').toggleClass('hide--me');

                                    if (!$J('.registration-failed').hasClass('hide--me')) {
                                        $J('.registration-failed').addClass('hide--me');
                                    }
                                }
                                else {
                                    if (data.ErrorMessage && data.ErrorMessage != '') {
                                        $J('.registration-failed p').html(data.ErrorMessage);
                                    }

                                    $J('.registration-failed').removeClass('hide--me');
                                }

                                canonHelper.hideSpinner();
                            });

                            post.fail(function () {
                                canonHelper.hideSpinner();
                            });
                        }
                    });
                }

                /*Update booking*/
                if ($J('.update-event-session-cta').length > 0) {
                    $J('.update-event-session-cta').off('click');
                    $J('.update-event-session-cta').on('click', function (e) {
                        e.preventDefault();
                        canonHelper.showSpinner();

                        var bookingStepsContainer = $J(this).closest('.event-booking-steps');
                        var key = $J('.event-key').val();
                        var tickets = $J(bookingStepsContainer).find('.select-ticket-number').val();
                        var sessionId = $J(this).closest('.event-session-item').attr('data-session-id');
                        var isFree = $J(this).hasClass("free");
                        var postData = {
                            SessionId: sessionId,
                            Tickets: tickets,
                            Key: key
                        };

                        var data = canonHelper.addAntiForgeryToken(postData);
                        var post = $.post('/booking-steps/eventbooking/updateeventbooking', data);

                        post.done(function (data) {
                            _eventBookingScope.navigateToPageOnUnsuccessful(data);
                            if (isFree) {
                                if (data) {
                                    $J(bookingStepsContainer).html(data).promise().done(function () {
                                        _eventBookingScope.initEventBooking();
                                        _eventBookingScope.navigateScreenToTop();
                                        _eventBookingScope.updateEventTrakerField(bookingStepsContainer.find(".wrapper-border"));
                                    });
                                }
                            }
                            else {
                                var bookingContainer = $J(bookingStepsContainer).find(".wrapper-border");
                                bookingContainer.attr("data-active", "0");
                                var currentStepContainer = $J(bookingStepsContainer).find(".wrapper-border[data-currentstep='3']");
                                currentStepContainer.attr("data-active", "1");
                                currentStepContainer.show();
                                _eventBookingScope.navigateScreenToTop();
                                _eventBookingScope.updateEventTrakerField(currentStepContainer);
                                var currentStep = currentStepContainer.data("currentstep");
                                _eventBookingScope.updateEventOrderDetails(currentStepContainer, currentStep);
                                _eventBookingScope.hideOrShowStep(bookingStepsContainer, currentStep);
                                $J(bookingStepsContainer).find(".booking-steps").removeClass("hide--me");
                                _eventBookingScope.showPaymentScreen(currentStepContainer, $J(".event-goback"));
                                _eventBookingScope.makeElementAsReadyOnly($J(".payment-section input,select"));
                            }
                            canonHelper.hideSpinner();
                        });

                        post.fail(function () {
                            canonHelper.hideSpinner();
                        });
                    });
                }
                if ($J('.edit-payment-details').length > 0) {
                    $J(".edit-payment-details").off('click');
                    $J(".edit-payment-details").on('click', function (e) {
                        e.preventDefault();
                        canonHelper.showSpinner();
                        var key = $J('.event-key').val();
                        var postData = {
                            key: key
                        };
                        var bookingStepsContainer = $J(this).closest('.event-booking-steps');
                        var data = canonHelper.addAntiForgeryToken(postData);
                        var post = $.post('/booking-steps/eventbooking/reloadpaymentstep', data);

                        post.done(function (data) {
                            _eventBookingScope.renderEventBookingStep3(bookingStepsContainer, data);
                            canonHelper.hideSpinner();
                        });

                        post.fail(function () {
                            canonHelper.hideSpinner();
                        });
                    });
                }

                //render free event captcha
                function renderAndRegisterFreeEventCaptcha() {
                    if ($J(".free-event-confirm-container").length > 0 && $J(".free-event-confirm-container").data("googlerecaptchasitekey")) {
                        $(".gCaptcha").html('');
                        if ($J(".free-event-confirm-container").data("isreload") === "True") {
                            canonHelper.getScript("https://www.google.com/recaptcha/api.js?onload=renderAndRegisterCaptcha&render=explicit").done(function (data) { }).fail(function () { });
                        }
                        else {
                            captchaWidgetId = grecaptcha.render('gCaptcha', {
                                'sitekey': $(".free-event-confirm-container").data("googlerecaptchasitekey"),
                                'callback': 'onReturnFreeEventCaptchaCallback'
                            });
                            grecaptcha.reset(captchaWidgetId);

                            $('.form-free-event-confirmation').find('#acceptfeeeventcondition').on("click", function () {
                                $(".free-event-confirmation").attr("disabled", "true");
                                $(".free-event-confirmation").removeClass("valid");
                                var response = grecaptcha.getResponse(captchaWidgetId);
                                if (response.length <= 0) {
                                    $(".error.recaptcha").text("You can't leave Captcha Code empty");
                                }
                                if ($(this).is(":checked") && response && response.length > 0) {
                                    $(".error.recaptcha").text("");
                                    $(".free-event-confirmation").removeAttr("disabled");
                                    $(".free-event-confirmation").addClass("valid");
                                }
                            });
                        }
                    }
                }

                renderAndRegisterFreeEventCaptcha();

                if ($J('.select-ticket-number').length > 0) {

                    function validateSessionCta(currentBookingButton, selectedNumberOfTickets, isEdit) {
                        var sessionAvailableSpot = parseInt($J(currentBookingButton).attr('data-available-spot'));
                        if (sessionAvailableSpot > 0) {
                            if (selectedNumberOfTickets > sessionAvailableSpot) {
                                $J(currentBookingButton).text('Not enough spots');
                                $J(currentBookingButton).attr('disabled', '');
                                $J(currentBookingButton).removeClass('active');
                            }
                            else {
                                $J(currentBookingButton).text(isEdit ? 'Update selection' : 'Make a booking');
                                $J(currentBookingButton).removeAttr('disabled');
                                if (!$J(currentBookingButton).hasClass('active')) {
                                    $J(currentBookingButton).addClass('active');
                                }
                            }
                        }
                    }

                    $J('.select-ticket-number').off("change");
                    $J('.select-ticket-number').on("change", function (e) {
                        var currentElement = $J(this);
                        var isEdit = $J(this).data("isedit");
                        var selectedNumberOfTickets = parseInt($J($J(currentElement).find('option')[e.target.selectedIndex]).val());
                        var eventSessionContainer = $J(currentElement).closest('.event-session-container');
                        eventSessionContainer.find('.event-session-cta, .update-event-session-cta').each(function () {
                            validateSessionCta($J(this), selectedNumberOfTickets, isEdit);
                        });
                    });
                }

                if ($J('.event-booking-identity-option').length > 0) {
                    $J('.event-booking-identity-option').off("change");
                    $J('.event-booking-identity-option').on("change", function (e) {
                        var currentElement = $J(this);
                        if ($J(currentElement).val() === 'anonymous') {
                            $J(".event-booking-step3-form").removeClass('hide--me');
                            $J(".event-booking-mycanon-login").addClass('hide--me');
                        }
                        else {
                            $J(".event-booking-step3-form").addClass('hide--me');
                            $J(".event-booking-mycanon-login").removeClass('hide--me');
                        }
                    });
                }
            }
        };

        return _eventBookingScope;

    })();

    $J(document).ready(function () {
        if (canonHelper !== undefined) {
            eventBooking.init();
        }
    });
})(jQuery);;
(function ($J) {
    var productSupport = (function () {
        var _productSupportScope = {
            init: function () {
                this.initPrePopulatedSupportOption();
                this.initPrePopulatedBusinessSupportOption();
                this.initSupportOptionsSelection();
                this.initBusinessSupportOptionsSelection();
                this.initProductSupportListingFilter();
                this.initProductSupportFilterByKeyword();
                this.initAutoSelectSupportOptionByQueryString();
            },

            productSearchAutoComplete: function (selectedOption, supportItemId, serviceAndRepair) {
                if ($(".product-support-thead") && $(".product-support-thead").length > 0) {
                    var element = $(".product-support-thead");
                    $(".product-support-thead").typeahead({
                        source: $.debounce(function (query, process) {
                            typeaheadSource(query, process, element, selectedOption, supportItemId);
                        },300),
                        minLength: 0
                    });

                    function typeaheadSource(query, response, el) {
                        var listContainer = $J(el).closest(".cb15,.cb15a").find(".product-support-container ul");
                        var container = listContainer.parent();

                        if (query.length >= 2) {
                            canonHelper.showSpinner();
                            var postTarget = serviceAndRepair ? "/content/search/typeaheadforserviceandrepair" : "/content/search/typeaheadforproductsupport";
                            var dataPost = { query: query, selectedOption: selectedOption, includeOption: selectedOption === "drivers", supportItemId: supportItemId };
                            if (serviceAndRepair) {
                                dataPost = { query: query, selectedOption: selectedOption, supportItemId: supportItemId };
                            }

                            var post = $.post(postTarget, dataPost, function (data) {
                                canonHelper.hideSpinner();

                                if (data && data.Products) {
                                    var template = $J("#product-support-template").html();
                                    var result = Mustache.to_html(template, data);
                                    container.removeClass("hide--me");
                                    listContainer.html(result);
                                    canonHelper.tileMarginFix(listContainer);
                                } else {
                                    if (!container.hasClass("hide--me")) {
                                        container.addClass("hide--me");
                                    }
                                }
                                //response(data);
                            }).fail(function () {
                                canonHelper.hideSpinner();
                            });
                        } else {
                            if (!container.hasClass("hide--me")) {
                                container.addClass("hide--me");
                            }
                        }

                        return {};
                    }

                    var spinnerVisible = false;

                    function showProgress() {
                        if (!spinnerVisible) {
                            $("div#spinner").fadeIn("fast");
                            $(".image-spinner").html("Loading");
                            spinnerVisible = true;
                        }
                    };

                    function hideProgress() {
                        if (spinnerVisible) {
                            var spinner = $("div#spinner");
                            spinner.stop();
                            spinner.fadeOut("fast");
                            spinnerVisible = false;
                        }
                    };
                }
            },

            initPrePopulatedSupportOption: function () {
                var supportOptionsBlock = $(".cb15 .options");
                if (supportOptionsBlock != undefined && supportOptionsBlock.length > 0) {
                    var supportqueryString = canonHelper.getQueryString("optionId");
                    if (supportqueryString != undefined && supportqueryString.length > 0) {
                        $(".cb15 .options button[data-support-option=" + supportqueryString + "]").click();
                        var targetId = $J(".cb15 .step2-heading");
                        if (targetId != undefined) {
                            $('html, body').animate({
                                scrollTop: targetId.offset().top - 50
                            }, 1000);
                        }
                    }
                }
            },

            initPrePopulatedBusinessSupportOption: function () {
                var supportOptionsBlock = $(".cb15a .options");
                if (supportOptionsBlock != undefined && supportOptionsBlock.length > 0) {
                    var supportqueryString = canonHelper.getQueryString("optionId");
                    if (supportqueryString != undefined && supportqueryString.length > 0) {
                        $(".cb15a .options button[data-support-option=" + supportqueryString + "]").click();
                        var targetId = $J(".cb15a .step2-heading");
                        if (targetId != undefined) {
                            $('html, body').animate({
                                scrollTop: targetId.offset().top - 50
                            }, 1000);
                        }
                    }
                }
            },

            initSupportOptionsSelection: function () {
                var optionType = "";
                var supportOptionsArrow = function () {
                    $J(".cb15 ul.list-category > li").each(function (event) {
                        if ($J(this).attr("data-url") && $J(this).attr("data-url") != "" && $J(this).find('.link.icomoon-ArrowRight').length === 0) {
                            $J(this).find('span[class*="icon-svg-accord"]').addClass("hide--me");
                            $J(this).find('button').append('<span class="link icomoon-ArrowRight"></span>');
                            $J(this).find('button span.link').hide().show(0);
                        } else {
                            $J(this).find('span[class*="icon-svg-accord"].hide--me').removeClass("hide--me");
                        }
                    });
                }

                var renderSupportOptionsCategoriesWithPagination = function () {
                    var templates = $J("#service-type-setp2-template").html();
                    var feed = $J(".cb15 .list-category");
                    var pageSize = 4;
                    var childrenCount = supportCategories.length;
                    if (supportCategories != undefined && supportCategories.length > 0) {

                        var result = "";
                        result += Mustache.to_html(templates,
                            { Categories: supportCategories, selectedOption: selectedOption, selectedOptionId: supportItemId, type: optionType });
                        if (childrenCount <= 4) {
                            $(".cb15 .more-container").addClass("hidden");
                        } else {
                            var reg = new RegExp("\\{0\\}", "gm");
                            $J(".cb15 .more-container button span:last-child").text($J(".cb15 .more-container button span:last-child").attr('data-text').replace(reg, childrenCount - pageSize));
                        }
                        feed.append(result);
                        if (currentindex === 0) {
                            $(".cb15 ul.list-category > li:lt(4)").removeClass('hide');
                        }
                        currentindex++;
                        supportOptionsArrow();
                    }
                };

                $(".cb15 .options").on("click", "button", function (event) {
                    var currentElement = $J(this);
                    var templateSearchBox = $J('#service-type-setp2-search-box-template').html();
                    var feedSearchBox = $J('.cb15 .step2-contents-container');
                    var parentItemId = $J(this).attr('data-associated-content');
                    $(".cb15 .support-section").removeClass("selected");
                    $(".cb15 .step2-contents-container").show();
                    totalCount = 0;
                    supportItemId = $J(this).attr('data-support-option');
                    selectedOption = $J(this).attr('data-label').toLowerCase().replace(/ /g, "-");
                    supportCategories = {};
                    currentindex = 0;
                    isLastPage = true;
                    childrenPageIndex = 0;
                    $J('.cb15 .list-category').html('');
                    if (parentItemId != undefined && supportItemId != undefined && supportItemId.length > 0) {

                        canonHelper.showSpinner();
                        var postData = { parentNodeId: parentItemId, supportOptionId: supportItemId };
                        var data = canonHelper.addAntiForgeryToken(postData);
                        var post = $J.post('/content-tile/productsupport/step2', data);

                        post.done(function (data) {
                            if (data != "") {

                                feedSearchBox.html(Mustache.to_html(templateSearchBox, { EnableSearchBox: data.EnableSearchBox, OptionalText: data.OptionalText, SelectedOption: selectedOption, SearchBoxCaptionText: data.SearchBoxCaptionText }));

                                if (data.Categories != undefined) {
                                    supportCategories = data.Categories;
                                    optionType = data.Type;
                                    renderSupportOptionsCategoriesWithPagination();
                                }

                                var serviceAndRepair = currentElement.attr("data-type") === "service";

                                _productSupportScope.productSearchAutoComplete(currentElement.attr("data-type"), supportItemId, serviceAndRepair);
                            }
                            canonHelper.hideSpinner();

                        });

                        post.fail(function () {
                            canonHelper.hideSpinner();
                        });
                    }
                });

                $(document).on('click', '.cb15 ul.list-category  li > button', function (event) {
                    $this = $(this);
                    $parent = $(this).parentsUntil($('ul.list-category')).last();
                    if ($this.parent().attr("data-url") && $this.parent().attr("data-url") != "") {
                        document.location = $this.parent().attr("data-url");
                        return null;
                    }
                    if ($this.find('.active').hasClass("open")) {
                        $('.cb15 ul.list-category .item.open').each(function (evt) {
                            $(this).find('span.open').addClass('active');
                            $(this).find('span.close').removeClass('active');
                            $(this).find('.content.open').removeClass('open');
                            $(this).removeClass('open');
                        });
                        $this.parent().addClass('open').find('.content').addClass('open');
                    } else {
                        $this.parent().removeClass('open').find('.content').removeClass('open');
                    }
                    $this.find('span.open, span.close').toggleClass('active');
                });
                $J(document).on('click', '.load-more-support-categories', function () {
                    canonHelper.showSpinner();
                    $('.cb15 ul.list-category > li').removeClass('hide');
                    $(".cb15 .more-container").addClass("hidden");
                    canonHelper.hideSpinner();
                });

                $J(document).on("click", ".cb19 .heading a.li-click", function () {
                    var $parent = $J(this).parentsUntil('.container').last();
                    // $J(this).find('.active').addClass('open');
                    if ($J(this).find('.active').hasClass("open")) {
                        $parent.find('.content.open').removeClass('open');
                        $parent.find('span.active').removeClass('active');
                        $parent.last().find('span:first-child').addClass('active');
                        $J(this).find("span:first-child").removeClass('active');
                        $J(this).find("span:last-child").addClass('active');
                        $J(this).closest(".item").find(".content").addClass('open');
                        TweenMax.fromTo($J(this).find("span:last-child"), 0.30, { css: { rotation: 0 } }, { css: { rotation: 135 } });
                    } else {
                        var $this = $J(this);
                        TweenMax.fromTo($J(this).find("span:last-child"), 0.30, { css: { rotation: 135 } }, {
                            css: { rotation: 0 }, onComplete: function () {
                                $this.find("span:first-child").addClass('active');
                                $this.find("span:last-child").removeClass('active');
                                $this.closest(".item").find(".content").removeClass('open');
                            }
                        });
                    }
                });
            },

            initBusinessSupportOptionsSelection: function () {
                $(".cb15a .options button[data-type='drivers']").on("click", function () {
                    var currentElement = $J(this);
                    supportItemId = $J(this).attr('data-support-option');
                    selectedOption = $J(this).attr('data-label').toLowerCase().replace(/ /g, "-");
                    _productSupportScope.productSearchAutoComplete(currentElement.attr("data-type"), supportItemId, false);
                });
                
                if ($(".cb15a .product-model-search-box, .cb15a .not-my-product-model-search-box") &&
                    $(".cb15a .product-model-search-box, .cb15a .not-my-product-model-search-box").length > 0) {
                    $(".cb15a .product-model-search-box, .cb15a .not-my-product-model-search-box").typeahead({
                        source: $.debounce(function (query, process) {
                            typeaheadSource(query, process);
                        },300),
                        minLength: 3,
                        items: "10",
                        autoSelect: false
                    });

                    function typeaheadSource(query, response) {
                        // This is going to make an HTTP GET request to the controller
                        canonHelper.showSpinner();
                        var post = $.post("/content/search/typeaheadforproduct", { query: query }, function (data) {
                            canonHelper.hideSpinner();
                            response(data);
                        }).fail(function () {
                            canonHelper.hideSpinner();
                        });

                        return post;
                    }
                }

                var formPrefilledValues = {};
                var supportOptionsArrow = function () {
                    $J(".cb15a ul.list-category > li").each(function (event) {
                        if ($J(this).attr("data-url") && $J(this).attr("data-url") != "" && $J(this).find('.link.icomoon-ArrowRight').length === 0) {
                            $J(this).find('span[class*="icon-svg-accord"]').addClass("hide--me");
                            $J(this).find('button').append('<span class="link icomoon-ArrowRight"></span>');
                            $J(this).find('button span.link').hide().show(0);
                        } else {
                            $J(this).find('span[class*="icon-svg-accord"].hide--me').removeClass("hide--me");
                        }
                    });
                }

                $(".cb15a .options").on("click", "button", function (event) {
                    $(".cb15a ul.list-category > li:lt(4)").removeClass('hide');
                    supportOptionsArrow();
                    var targetId = $J(".cb15a .step2-heading");
                    if (targetId != undefined) {
                        $('html, body').animate({
                            scrollTop: targetId.offset().top - 50
                        }, 1000);
                    }
                });

                $J(".cb15a .load-more-support-categories").on("click", function () {
                    canonHelper.showSpinner();
                    $('.cb15a ul.list-category > li').removeClass('hide');
                    $(".cb15a .more-container").addClass("hidden");
                    canonHelper.hideSpinner();
                });

                var callSerialFinder = function (serialNumber) {
                    return $J.getJSON("/content-tile/productsupport/getproductbyserialnumber?serialNumber=" + $.trim(serialNumber));
                };

                var callProductModelFinder = function (model) {
                    return $J.getJSON("/content-tile/productsupport/getproductbymodel?model=" + $.trim(model));
                };

                $J(".cb15a .filter-container select").prop('selectedIndex', 0);
                $J(".cb15a .filter-container select").on("change", function (e) {
                    var $this = $J(this);
                    e.preventDefault();
                    var template = $J('#how-to-serial-number-template').html();
                    var feed = $J('.serial-number-modal-body');

                    var selectedValue = $this.find(':selected').val();
                    if (selectedValue != "") {

                        canonHelper.showSpinner();
                        var post = $J.getJSON('/content-tile/productsupport/gethowtofindserialnumberinfo?atricleId=' + selectedValue);

                        post.done(function (data) {
                            if (data != "") {
                                var result = Mustache.to_html(template, { content: data });
                                feed.html(result);
                            }
                            canonHelper.hideSpinner();
                        });

                        post.fail(function () {
                            canonHelper.hideSpinner();
                        });
                    }
                    else {
                        feed.html("<p>Please select a category</p>");
                    }
                });

                $J(".cb15a #serialnumber-search-box").on("keypress", function (e) {
                    var key = e.keyCode;
                    $J(this).parent().addClass("is-searching");
                    // If enter is pressed
                    if (key == 13) {
                        formPrefilledValues["ProductSerialNumber"] = $.trim($J(this).val());
                        $J(".cb15a").find("#service .section").removeClass("active");
                        $J(this).parent().removeClass("is-searching");
                        var templateSerialNumber = $J("#serial-number-finder-template").html();
                        var templateProductSelection = $J("#product-selection-template").html();
                        var feedSerialNumber = $J("#serial-result-found");
                        var feedProductSelection = $J("#correct-product");
                        canonHelper.showSpinner();
                        var post = callSerialFinder($J(this).val());

                        post.done(function (data) {
                            if (data != undefined && data != "" && $.trim(data.Name) != "") {
                                var resultSerialNumber = Mustache.to_html(templateSerialNumber, { Product: data });
                                feedSerialNumber.html(resultSerialNumber);

                                formPrefilledValues["ProductName"] = $J(".cb15a .product-model-found").data("model");

                                var resultProductSelection = Mustache.to_html(templateProductSelection, { Product: data });
                                feedProductSelection.html(resultProductSelection);
                                $J(".cb15a").find("#service #serial-result-found").addClass("active");
                            }
                            else {
                                $J(".cb15a").find("#service #incorrect-serial").addClass("active");
                            }
                            canonHelper.hideSpinner();
                        });

                        post.fail(function () {
                            canonHelper.hideSpinner();
                        });
                    }
                });

                $J(".cb15a .product-model-search-box, .cb15a .not-my-product-model-search-box").on("keypress", function (e) {
                    var key = e.keyCode;
                    // If enter is pressed
                    if (key == 13) {
                        formPrefilledValues["ProductName"] = $.trim($J(this).val());
                        var template = $J("#product-selection-template").html();
                        var feed = $J("#correct-product");
                        canonHelper.showSpinner();
                        var post = callProductModelFinder($J(this).val());

                        post.done(function (data) {
                            if (data != undefined && data != "" && $.trim(data.Name) != "") {
                                var result = Mustache.to_html(template, { Product: data });
                                feed.html(result);
                                $J(".cb15a").find("#service .section").removeClass("active");
                                $J(".cb15a").find("#service #correct-product").addClass("active");
                                $J(".cb15a").find("#service #correct-product a.back").attr("data-section-id", "incorrect-serial");
                            }
                            else {
                                $J(".cb15a").find("#service .incorrect-product-text").addClass("active");
                            }
                            canonHelper.hideSpinner();
                        });

                        post.fail(function () {
                            canonHelper.hideSpinner();
                        });
                    }
                });

                $J(document).on("click", ".cb15a .clear-search", function (e) {
                    e.preventDefault();
                    $(this).parent().removeClass("is-searching");
                    $(".cb15a #serialnumber-search-box").val("");
                });


                $J(document).on("keyup", ".cb15a #serialnumber-search-box", function (e) {
                    var key = e.keyCode;
                    if (key == 8 || key == 46) {
                        if ($(this).val() == "") {
                            $(this).parent().removeClass("is-searching");
                        }
                    }
                });

                $J(document).on("click", ".cb15a .product-model-search-container a", function (e) {
                    e.preventDefault();
                    var model = $(this).closest(".product-model-search-container").find(".product-model-search-box").val();
                    var template = $J("#product-selection-template").html();
                    var feed = $J("#correct-product");
                    canonHelper.showSpinner();
                    var post = callProductModelFinder(model);

                    post.done(function (data) {
                        if (data != undefined && data != "" && $.trim(data.Name) != "") {
                            formPrefilledValues["ProductName"] = $.trim(model);
                            var result = Mustache.to_html(template, { Product: data });
                            feed.html(result);
                            $J(".cb15a").find("#service .section").removeClass("active");
                            $J(".cb15a").find("#service #correct-product").addClass("active");
                            $J(".cb15a").find("#service #correct-product a.back").attr("data-section-id", "incorrect-serial");
                        }
                        else {
                            $J(".cb15a").find("#service .incorrect-product-text").addClass("active");
                        }
                        canonHelper.hideSpinner();
                    });

                    post.fail(function () {
                        canonHelper.hideSpinner();
                    });
                });

                $J(document).on("click", ".cb15a .not-my-product-search-container a", function (e) {
                    e.preventDefault();
                    var model = $(this).closest(".not-my-product-search-container").find(".not-my-product-model-search-box").val();
                    var template = $J("#product-selection-template").html();
                    var feed = $J("#correct-product");
                    canonHelper.showSpinner();
                    var post = callProductModelFinder(model);

                    post.done(function (data) {
                        if (data != undefined && data != "" && data.Name != "") {
                            formPrefilledValues["ProductName"] = $.trim(model);
                            var result = Mustache.to_html(template, { Product: data });
                            feed.html(result);
                            $J(".cb15a").find("#service .section").removeClass("active");
                            $J(".cb15a").find("#service #correct-product").addClass("active");
                            $J(".cb15a").find("#service #correct-product a.back").attr("data-section-id", "product-search");
                        }
                        else {
                            $J(".cb15a").find("#service .incorrect-product-text").addClass("active");
                        }
                        canonHelper.hideSpinner();
                    });

                    post.fail(function () {
                        canonHelper.hideSpinner();
                    });
                });

                $J(document).on("click", ".cb15a .section-trigger", function (e) {
                    e.preventDefault();
                    var sectionId = $(this).data("section-id");
                    $(".cb15a").find("#service .section,#service .sub-section").removeClass("active");
                    $(".cb15a").find("#" + sectionId).addClass("active");
                });

                $J(document).on("click", ".cb15a .sub-section-trigger", function (e) {
                    e.preventDefault();
                    var sectionId = $(this).data("section-id");
                    $(".cb15a").find("#service .sub-section").removeClass("active");
                    $(".cb15a").find("#" + sectionId).addClass("active");
                });

                $J(document).on("click", ".cb15a .tab", function (e) {
                    e.preventDefault();
                    var sectionId = $(this).data("tab-id");
                    formPrefilledValues["ErrorType"] = $.trim(sectionId);
                    formPrefilledValues["ErrorDescription"] = $.trim($(this).data("internalcode"));

                    $(".cb15a").find("#service .tab-content,#service .tab").removeClass("active");
                    $(".cb15a").find("#" + sectionId).addClass("active");
                    $(this).addClass("active");
                });

                $J(document).on("change", ".cb15a #error-dropdown", function () {
                    $(".cb15a").find("#error .sub-section").removeClass("active");
                    $("#" + $(this).val()).addClass("active");

                    formPrefilledValues["ErrorType"] = "error";
                    formPrefilledValues["ErrorDescription"] = $.trim($(this).find(':selected').data("internalcode"));
                });

                $J(document).on("click", ".cb15a .issue-select a", function (e) {
                    var $this = $J(this);
                    var type = $this.parent().find(".product-name").find(':selected').val();
                    if (type != "") {
                        var description = $this.parent().find("input").val();
                        formPrefilledValues["ErrorType"] = $.trim(type);
                        formPrefilledValues["ErrorDescription"] = $.trim(description);
                        canonHelper.setCookie("CANON_FORMCOLLECTION", encodeURIComponent(JSON.stringify(formPrefilledValues)), 0.01);
                        var formUrl = $(".service-repairs-options").data("form-url");
                        window.location.href = formUrl;
                    }
                    else {
                        alert("Please select an issue");
                    }
                });

                $J(document).on("click", ".cb15a .tab-content .req a", function (e) {
                    canonHelper.setCookie("CANON_FORMCOLLECTION", encodeURIComponent(JSON.stringify(formPrefilledValues)), 0.01);
                    var formUrl = $(".service-repairs-options").data("form-url");
                    window.location.href = formUrl;
                });
            },


            initProductSupportListingFilter: function () {
                if ($J(".load-more-product-support-listing").attr('data-is-last-page') == "True") {
                    $J('.load-more-product-support-listing').hide();
                } else {
                    $J('.load-more-product-support-listing').show();
                }

                $J('.load-more-product-support-listing').off('click');
                $J(".load-more-product-support-listing").on("click", function () {
                    var $this = $J(this);
                    var currentPageIndex = $this.attr('data-current-index');
                    var totalProductDisplayedOnPage = $this.attr('data-total-product-displayed-on-page');
                    var isLastPage = $this.attr('data-is-last-page');
                    if (isLastPage.toLowerCase() === "false" || !isLastPage) {
                        currentPageIndex++;
                    }

                    $J(this).blur();

                    _productSupportScope.callProductSupportListingFeed(currentPageIndex, totalProductDisplayedOnPage, true, $J(".subcategory-filter .subcategory-filter-select.active"));
                });

                $J(".subcategory-filter .subcategory-filter-select").on("click", function () {
                    $J(".subcategory-filter .subcategory-filter-select").removeClass("active");
                    $J(this).addClass("active");
                    var searchBar = $J(this).closest('.cl01').find('.support-products-feed-keyword');

                    if (!$J(this).hasClass('loaded')) {
                        var reg = new RegExp("\\{0\\}", "gm");
                        var $el = {};
                        var loadmoreText = {};
                        var selectedCategory = $J(this).attr('data-category-id');
                        if (selectedCategory === 'all') {
                            $el = $('ul.support-products-container > li').fadeIn("slow");
                            if ($J(".products-left").attr('data-text') != undefined) {
                                loadmoreText = $J(".products-left").attr('data-text').replace(reg, $el.length);
                                $J(".products-left").html(loadmoreText);
                            }
                        } else {
                            $el = $('.' + selectedCategory).fadeIn("slow");
                            $('ul.support-products-container > li').not($el).hide();
                            if ($J(".products-left").attr('data-text') != undefined) {
                                loadmoreText = $J(".products-left").attr('data-text').replace(reg, $el.length);
                                $J(".products-left").html(loadmoreText);
                            }
                        }

                        $J(".subcategory-filter .subcategory-filter-select").removeClass('loaded');

                        if ($J(this).attr('data-is-all') === "0") {
                            $J(searchBar).val('');
                            $J(searchBar).attr('data-keyword', '');
                        }

                        $J(this).addClass('loaded');

                        _productSupportScope.callProductSupportListingFeed(0, 0, false, $J(this));
                    }
                    else if ($J(this).attr('data-is-all') === "1" && searchBar.val() && searchBar.val().length > 0) {
                        $J(searchBar).val('');
                        $J(searchBar).attr('data-keyword', '');
                        _productSupportScope.callProductSupportListingFeed(0, 0, false, $J(this));
                    }
                });
            },

            initProductSupportFilterByKeyword: function () {
                $J('.support-products-feed-keyword').keypress(function (e) {
                    if (e.which === 13) {
                        var keyword = $J(this).val();
                        var currentKeyword = $J(this).attr('data-keyword');
                        if (currentKeyword == undefined || currentKeyword !== keyword) {
                            $J(this).attr('data-keyword', keyword);
                            var loadedFilter = $J(this).closest(".cl01").find(".subcategory-filter-select.loaded");
                            if (loadedFilter && loadedFilter.length > 0) {
                                $J(loadedFilter).removeClass('loaded');
                            }
                            var filterAll = $J(this).closest(".cl01").find('.subcategory-filter-select[data-is-all="1"]')[0];
                            $J(filterAll).trigger('click');
                        }
                    }
                });
            },

            initAutoSelectSupportOptionByQueryString: function () {
                if ($J('.cb15') && $J('.cb15').length > 0) {
                    $J(document).ready(function () {
                        var optionID = canonHelper.getQueryString("optionId");
                        if (optionID) {
                            $('.driver button[data-support-option="' + optionID + '"] ').removeClass('selected');
                            $('.driver button[data-support-option="' + optionID + '"] ').trigger('click');
                        }
                    });
                                     
                }               

            },

            callProductSupportListingFeed: function (currentPageIndex, totalProductDisplayedOnPage, isLoadMore, el) {

                var componentEl = $J(el).closest('.cl01');
                var template = $J(componentEl).find('.support-products-container-template').html();
                var feed = $J(componentEl).find('ul.support-products-container');
                var category = $J(componentEl).find(".subcategory-filter .subcategory-filter-select.active").attr('data-category-id');
                var isAll = $J(componentEl).find(".subcategory-filter .subcategory-filter-select.active").attr('data-is-all');
                var keyword = $J(componentEl).find('.support-products-feed-keyword').attr('data-keyword');
                var selectedTitle = $J(el)[0].innerText != "All" ? $J(el)[0].innerText : '';
                var regex = new RegExp("(.*)((?:es|ess)$)");
                var source = $J(".total-products-count").data("productcategory").length != 0 ? $J(".total-products-count").data("productcategory") : !regex.test(selectedTitle) ? selectedTitle.replace(/[e']s$/, '').replace(/([^siou])s/, '$1') : selectedTitle;
                if (source.length == 0) {
                    source = "product";
                }
                source = source.toLowerCase();
                canonHelper.showSpinner();

                var postData = {
                    SelectedCategory: category,
                    Keyword: keyword,
                    PageIndex: currentPageIndex,
                    TotalProductDisplayedOnPage: totalProductDisplayedOnPage,
                    IsAllSubcategorySupportPages: isAll === "1" ? true : false,
                    IsLoadMore: isLoadMore
                };

                var data = canonHelper.addAntiForgeryToken(postData);
                var post = $J.post('/content-tile/productsupport/getsupportproductlisting', data);

                post.done(function (data) {
                    if (data != "") {
                        if (data.SupportProducts != undefined) {
                            var selectedOption = $J('.support-product-listing-container').attr('data-selected-option');
                            var result = Mustache.to_html(template, { SupportProducts: data.SupportProducts, SelectedOption: selectedOption });

                            if (isLoadMore) {
                                feed.append(result);
                            } else {
                                feed.html(result);
                            }

                            if (data.IsLastPage) {
                                $J('.load-more-product-support-listing').hide();
                            } else {
                                $J(".load-more-product-support-listing").attr('data-current-index', data.CurrentPageIndex);
                                $J(".load-more-product-support-listing").attr('data-total-product-displayed-on-page', data.TotalProductsDisplayedOnPage);
                                $J(".load-more-product-support-listing").attr('data-is-last-page', data.IsLastPage);

                                $J('.load-more-product-support-listing').show();
                            }

                            var counterText = '';
                            if (postData.Keyword == undefined || (postData.Keyword != undefined && $J.trim(postData.Keyword).length === 0)) {
                                var reg1 = new RegExp("\\{0\\}", "gm");
                                var reg2 = new RegExp("\\{1\\}", "gm");
                                var reg3 = new RegExp("\\{2\\}", "gm");
                                counterText = $J(".total-products-count").attr('data-text').replace(reg1, data.TotalProductCount == 1 ? "is" : "are").replace(reg2, data.TotalProductCount).replace(reg3, (data.TotalProductCount == 1 || regex.test(source)) ? source : source + "s");
                            }
                            else {
                                counterText = $J.parseHTML("There " + (data.TotalProductCount == 1 ? "is" : "are") + " " + data.TotalProductCount + " " + ((data.TotalProductCount == 1 || regex.test(source)) ? source : source + "s") + " for <strong>" + postData.Keyword + ".</strong>");
                            }

                            $J(".total-products-count").html(counterText);

                            var loadmoreCounterText = "(" + data.TotalProductLeftCount + " " + ((!regex.test(source) && data.TotalProductLeftCount != 1) ? source + "s" : source) + " left)";
                            $J(".products-left").html(loadmoreCounterText);
                        }
                        canonHelper.tileMarginFix($J(feed));
                    }
                    canonHelper.hideSpinner();
                });

                post.fail(function () {
                    canonHelper.hideSpinner();
                });
            }
        };

        return _productSupportScope;

    })();

    $J(document).ready(function () {
        if (canonHelper !== undefined) {
            productSupport.init();
        }
    });
})(jQuery);;
(function($J) {
    var projectLeanne = (function() {
        var _projectLeanneScope = {
            init: function() {
                this.initProductPrinterTypeAhead();
            },

            initProductPrinterTypeAhead: function() {
                var $leanneProductSearch = $J(".leanne-product-search");
                if ($leanneProductSearch && $J($leanneProductSearch).length > 0) {
                    var $printerSearchBox =  $J($leanneProductSearch).find(".product-printer-search-box");
                    var $printerSearchButton = $J($leanneProductSearch).find(".product-printer-search");
                    var $productSearchStartItem = $printerSearchBox.attr("data-search-start-item");
                    var $assistPageGuid = $printerSearchBox.attr("data-assist-page-guid");
                    var productWithContentHelpList = {};

                    function typeaheadSource(query, process) {
                        canonHelper.showSpinner();
                        var postData = {
                            query: query,
                            productSearchStartItemId: $productSearchStartItem,
                            assistPageGuid: $assistPageGuid
                        };
                        var data = canonHelper.addAntiForgeryToken(postData);
                        var post = $J.post('/content-tile/leanne/getprinterproductswithhelp', data);
                        post.done(function(data) {
                            var productNames = [];
                            productWithContentHelpList = {};

                            $J.each(data, function(i, productWithHelpContent) {
                                productWithContentHelpList[productWithHelpContent.Heading] = productWithHelpContent;
                                productNames.push(productWithHelpContent.Heading);
                            });

                            canonHelper.hideSpinner();

                            process(productNames);
                        });

                        post.fail(function() {
                            canonHelper.hideSpinner();
                        });
                    }

                    $J($printerSearchButton).off('click');
                    $J($printerSearchButton).on('click', function(e) {
                        e.preventDefault();
                        var $errorMessageContainer = $J($leanneProductSearch).find('.product-not-supported-result');
                        if (!$J($errorMessageContainer).hasClass('hide--me')) {
                            $J($errorMessageContainer).addClass('hide--me');
                        }

                        var selectedProductUrl = $J($printerSearchBox).attr('data-product-url');
                        if (selectedProductUrl && selectedProductUrl.length > 0) {
                            window.location.href = selectedProductUrl;
                        } else {
                            $J($errorMessageContainer).removeClass('hide--me');
                        }
                    });

                    $J($printerSearchBox).typeahead({
                        source: $.debounce(function(query, process) {
                            typeaheadSource(query, process);
                        }, 300),
                        minLength: 2,
                        items: "4",
                        addItem: "Other",
                        highlighter: function(item) {
                            var regex = new RegExp('(' + this.query + ')', 'gi');
                            return item.replace(regex, "<strong>$1</strong>");
                        },
                        updater: function(item) {
                            var selectedProduct = productWithContentHelpList[item];
                            if (selectedProduct && selectedProduct.ProductUrl) {
                                $J($printerSearchBox).attr('data-product-url', selectedProduct.ProductUrl);
                            } else {
                                $J($printerSearchBox).attr('data-product-url', '');
                            }

                            $J($printerSearchBox).val(item);
                            $J($printerSearchButton).trigger('click');
                            return item;
                        }
                    });

                    $J($leanneProductSearch).on('keyup', '.product-printer-search-box', function(e) {
                        if (e.which == 13) {
                            $J($printerSearchButton).trigger('click');
                        }
                    });
                }
            }
        };

        return _projectLeanneScope;

    })();

    $J(document).ready(function() {
        if (canonHelper !== undefined) {
            projectLeanne.init();
        }
    });
})(jQuery);;
(function ($J) {
    var fastBusiness = (function () {
        var _fastBusinessScope = {
            init: function () {
                this.initFastBusinessFeedFilter();
                this.initFastBusinessFeedLoadMore();
                this.initFastBusinessResourceFeedFilter();
                this.initFastBusinessResourceFeedKeyword();
                this.initFastBusinessResourceFeedLoadMore();
                this.initContributorsLoadMore();
                this.initDownloadResourceForm();
                this.initDownloadResourceFormOnSubmit();
            },

            initFastBusinessFeedFilter: function () {
                //List of product Filter by, on desktop
                $J(".fast-business-feed-filter-container li").on('click', function () {
                    if (!$J(this).hasClass('filtered')) {
                        var tileContainer = $J(this).closest('.cf06').siblings('.cf08a').find('.fast-business-feed-list');

                        var postData = {
                            CurrentPageIndex: 0,
                            PageSize: 11,
                            SelectedFilterKey: $J(this).attr('data-filter'),
                            IsLoadMore: false,
                            ApplyFilter: true
                        };

                        $J(this).parent('ul').find('li').each(function () {
                            $J(this).removeClass("active");
                            $J(this).removeClass("filtered");
                        });

                        $J(this).addClass("active");
                        $J(this).addClass("filtered");

                        $J(this).closest('.fast-business-feed-filter-container').find('option').each(function () {
                            $J(this).removeAttr('selected');

                            if ($J(this).val() === postData.SelectedFilterKey) {
                                $J(this).attr('selected', '');
                                $J(this).parent('select').val(postData.SelectedFilterKey);
                            }
                        });

                        _fastBusinessScope.getFastBusinessFeed(postData, tileContainer, true);
                    }
                });

                //List of product Filter by, on mobile
                $J(".fast-business-feed-filter-container select").change(function () {

                    var selectedFilter = '';
                    $(this).find('option:selected').each(function () {
                        selectedFilter = $(this).val();
                        $J(this).removeAttr('selected');
                    });

                    $J(this).attr('selected', '');

                    if ($J(this).closest('.mobile').css('display') !== 'none') {
                        $J(this).closest('.fast-business-feed-filter-container').find('li').each(function () {
                            if ($J(this).attr('data-filter') === selectedFilter) {
                                $J(this).trigger('click');
                            }
                        });
                    }

                });
            },

            initFastBusinessFeedLoadMore: function () {
                $J('.fast-business-load-more-feed a').on('click', function (e) {
                    e.preventDefault();

                    var container = $J(this).closest('.cf08a').siblings('.cf06');

                    var selectedFilter = '';
                    $J(container).find('.fast-business-feed-filter-container li').each(function () {
                        if ($J(this).hasClass('active')) {
                            selectedFilter = $J(this).attr('data-filter');
                        }
                    });

                    var tileContainer = $J(this).parent().siblings('.fast-business-feed-list');

                    var currentPageIndex = $J(this).attr("data-current-page");
                    var pageToRender = parseInt(currentPageIndex) + 1;

                    var ParentId = $J("#parentId").val();
                    var postData = {
                        CurrentPageIndex: pageToRender,
                        PageSize: 11,
                        SelectedFilterKey: selectedFilter,
                        IsLoadMore: true,
                        ParentId: ParentId
                    };

                    $J(this).blur();
                    _fastBusinessScope.getFastBusinessFeed(postData, tileContainer, false);
                });
            },

            getFastBusinessFeed: function (postData, tileContainer, replaceHtml) {
                canonHelper.showSpinner();

                var data = canonHelper.addAntiForgeryToken(postData);
                var post = $J.post("/content-tile/fastbusiness/getfastbusinesshomefeed", data);

                post.done(function (data) {
                    var template;
                    // Try loading the external template files
                    $.when($.get("/mustachetemplates/content-listing-feed.html", function (source) { template = source; }))
                        .then(function () {
                            var noDataFoundEl = $J(tileContainer).parent().find(".fast-business-related-article-feed-empty");
                            var loadMoreEl = $J(tileContainer).parent().find(".fast-business-load-more-feed a");
                            var loadMoreContainerEl = $J(tileContainer).parent().find(".fast-business-load-more-feed");

                            if (data.ContentListingFeedSkinnyTiles && data.ContentListingFeedSkinnyTiles.length > 0) {
                                var result = Mustache.to_html(template, data);
                                noDataFoundEl.slideUp(500);

                                if (replaceHtml) {
                                    $J(tileContainer).html(result);
                                } else {
                                    $J(tileContainer).append(result);
                                }

                                $J(tileContainer).slideDown(500);
                                canonHelper.constructVideoElement();
                                canonHelper.tileMarginFix($J(tileContainer));

                            }
                            else {
                                if (noDataFoundEl.hasClass("hide--me")) {
                                    noDataFoundEl.removeClass("hide--me");
                                }

                                $J(tileContainer).slideUp(500);
                                noDataFoundEl.slideDown(500);
                            }

                            if (data && data.IsNextPageAvailable) {
                                var loadMoreText = "<span>Load more articles</span><br>" + "(" + data.NextItemToDisplayed + ") articles left";
                                $J(loadMoreEl).html(loadMoreText);
                                $J(loadMoreEl).attr("data-current-page", data.CurrentPageIndex);
                                $J(loadMoreContainerEl).removeClass('hide--me');
                            } else {
                                if (!loadMoreContainerEl.hasClass('hide--me')) {
                                    loadMoreContainerEl.addClass('hide--me');
                                }
                            }

                            canonHelper.hideSpinner();

                        },
                        function () {
                            // templates not loaded
                            var templateError = 'Error: Could not load plugin templates. Check the paths and ensure they have been uploaded. Paths will be wrong if you do not run this from a web server.'; console.log(templateError);
                            canonHelper.hideSpinner();
                        });
                });

                post.fail(function () {
                    canonHelper.hideSpinner();
                });

                post.always(function () {
                    //$J('.load-more-feed button').prop('disabled', false).removeClass('loading');
                });
            },

            initFastBusinessResourceFeedFilter: function () {
                $J('.filter-a').on('click', function () {
                    var filterToggleButton = $J(this);
                    var resourceFilterContainer = $J(filterToggleButton).closest('.nv15').find('.resource-filter-container');
                    $J(resourceFilterContainer).toggleClass('active');
                });

                //desktop
                $J('.resource-filter-key').on('click', function (el) {
                    el.preventDefault();

                    $J(this).closest('.nv15.filter-container').find('.resource-feed-keyword').val('');
                    $J(this).closest('.nv15.filter-container').find('.resource-feed-keyword').attr('data-keyword', '');

                    var filterKey = $J(this).attr('data-filter-key');
                    $J(this).closest('.resource-filter-container').attr('data-selected-filter', filterKey);
                    var filterContainer = $J(this).closest('.filter-container');
                    $J(filterContainer).find('.filter-a').text($J(this).text());
                    var tileContainer = filterContainer.siblings('.feed-container').find(".tile-container");

                    var currentElement = $J(this);
                    $(currentElement).closest('ul').find('.resource-filter-key.under').removeClass('under');


                    if (!$J(this).hasClass('under')) {
                        $J(this).addClass('under');
                    }

                    $J(this).closest('.nv15.filter-container').find('.mobile option').each(function () {
                        $J(this).removeAttr('selected');

                        if ($J(this).attr('data-filter-key') === filterKey) {
                            $J(this).attr('selected', '');
                            $J(this).parent('select').val(filterKey);
                        }
                    });

                    var postData = {
                        PageIndex: 0,
                        SelectedFilter: filterKey,
                        Keyword: ''
                    };

                    _fastBusinessScope.getFastBusinessResourceFeed(postData, tileContainer, true);
                    $J(filterContainer).find('.resource-filter-container').toggleClass('active');
                });

                //mobile
                $J(".fast-business-resource-feed-filter").on("change", function (e) {
                    var selectedFilter = $J(this).find(':selected').attr('data-filter-key');

                    if ($J(this).closest('.mobile').css('display') !== 'none') {
                        $J(this).closest('.nv15.filter-container').find('li').each(function () {
                            if ($J(this).attr('data-filter') === selectedFilter) {
                                $J(this).trigger('click');
                            }
                        });
                    }

                });
            },

            initFastBusinessResourceFeedKeyword: function () {
                $J('.resource-feed-keyword').keypress(function (e) {
                    if (e.which === 13) {
                        var keyword = $J(this).val();
                        var currentKeyword = $J(this).attr('data-keyword');
                        if (currentKeyword == undefined || currentKeyword !== keyword) {
                            searchByKeyword(keyword, $J(this));
                            $J(this).attr('data-keyword', keyword);
                        }
                    }
                });

                function searchByKeyword(keyword, el) {

                    var filterContainer = $J(el).closest('.filter-container');
                    var tileContainer = filterContainer.siblings('.feed-container').find(".tile-container");

                    filterContainer.find('select.fast-business-resource-feed-filter option:selected').removeAttr('selected');
                    var firstCategoryOption = filterContainer.find('select.fast-business-resource-feed-filter option:first');
                    if (firstCategoryOption && !firstCategoryOption.attr('selected')) {
                        firstCategoryOption.attr('selected', '');
                    }

                    var searchBar = filterContainer.find('.filter-container .search-container');
                    if (searchBar) {
                        $(searchBar).find('input').attr('data-keyword', keyword);
                    }

                    //Reset filter
                    filterContainer.find(".resource-filter-container").attr('data-selected-filter', '');
                    filterContainer.find('.resource-filter-container li a.under').each(function () {
                        $(this).removeClass('under');
                    });

                    //select 'All Resource'
                    var firstCategoryFilterOption = filterContainer.find('.resource-filter-container li:first');
                    if (firstCategoryFilterOption) {
                        if (!$(firstCategoryFilterOption).find('a').hasClass('under')) {
                            $(firstCategoryFilterOption).find('a').addClass('under');
                        }
                        filterContainer.find(".filter-a").text($(firstCategoryFilterOption).find('a').text());
                    }

                    //fast-business-resource-feed-filter
                    $J(filterContainer).find('.select.fast-business-resource-feed-filter option:selected').each(function () {
                        $(this).removeAttr('selected');
                    });

                    $J(filterContainer).find('.select.fast-business-resource-feed-filter option:first').attr('selected', 'selected');

                    var postData = {
                        PageIndex: 0,
                        SelectedFilter: '',
                        Keyword: keyword
                    };

                    _fastBusinessScope.getFastBusinessResourceFeed(postData, tileContainer, true);
                }
            },

            initFastBusinessResourceFeedLoadMore: function () {
                $J('.fast-business-resource-load-more-feed a').on('click', function (e) {
                    e.preventDefault();

                    var container = $J(this).closest('.feed-container').siblings('.filter-container');
                    var selectedFilter = $J(container).find('.resource-filter-container').attr('data-selected-filter');
                    var keyword = $J(container).find('input.resource-feed-keyword').attr('data-keyword');
                    var tileContainer = $J(this).closest('.feed-container').find('.tile-container');

                    var currentPageIndex = $J(this).attr("data-current-page");
                    var pageToRender = parseInt(currentPageIndex) + 1;

                    var postData = {
                        PageIndex: pageToRender,
                        SelectedFilter: selectedFilter ? selectedFilter : '',
                        Keyword: keyword ? keyword : ''
                    };

                    $J(this).blur();
                    _fastBusinessScope.getFastBusinessResourceFeed(postData, tileContainer, false);
                });
            },

            getFastBusinessResourceFeed: function (postData, tileContainer, replaceHtml) {
                canonHelper.showSpinner();

                var data = canonHelper.addAntiForgeryToken(postData);
                var post = $J.post("/content-tile/fastbusiness/getresourcelist", data);

                post.done(function (data) {
                    var template = $J("#resources-template").html();
                    var loadMoreEl = $J(tileContainer).closest('.feed-container').find(".fast-business-resource-load-more-feed a");
                    var loadMoreContainerEl = $J(loadMoreEl).parent();

                    var noDataFoundContainer = $J(tileContainer).find('.fast-business-resource-feed-empty');

                    if (data.SkinnyResourcePages && data.SkinnyResourcePages.length > 0) {
                        $J(tileContainer).removeClass('hide--me');
                        if (!$(noDataFoundContainer).hasClass('hide--me')) {
                            $(noDataFoundContainer).addClass('hide--me');
                        }

                        var result = Mustache.to_html(template, data);
                        if (replaceHtml) {
                            $J(tileContainer).html(result);
                        } else {
                            $J(tileContainer).append(result);
                        }

                        $J(tileContainer).slideDown(500);
                        canonHelper.constructVideoElement();
                        canonHelper.tileMarginFix($J(tileContainer));
                    }
                    else {
                        $(noDataFoundContainer).removeClass('hide--me');
                        if (!$(tileContainer).hasClass('hide--me')) {
                            $(tileContainer).addClass('hide--me');
                        }
                    }

                    if (data && data.IsNextPageAvailable) {
                        var loadMoreText = "<span>Load more " + data.TilesTypeForLoadMore + "</span><br>" + "(" + data.NextItemToDisplayed + ") " + data.TilesCounterForLoadMore + " left";
                        $J(loadMoreEl).html(loadMoreText);
                        $J(loadMoreEl).attr("data-current-page", data.CurrentPageIndex);
                        $J(loadMoreContainerEl).removeClass('hide--me');
                    } else {
                        if (!loadMoreContainerEl.hasClass('hide--me')) {
                            loadMoreContainerEl.addClass('hide--me');
                        }
                    }

                    canonHelper.hideSpinner();
                });

                post.fail(function () {
                    canonHelper.hideSpinner();
                });

                post.always(function () {
                    //$J('.load-more-feed button').prop('disabled', false).removeClass('loading');
                });
            },

            initContributorsLoadMore: function () {
                $J('.contributor-load-more-feed a').on('click', function (e) {
                    e.preventDefault();

                    var container = $J(this).closest('.cl04');
                    var tileContainer = $J(container).find('ul');
                    var loadMoreEl = $J(container).find(".contributor-load-more-feed a");
                    var loadMoreContainerEl = $J(loadMoreEl).parent();


                    canonHelper.showSpinner();
                    var post = $J.get('/content-tile/fastbusiness/getcontributorlist');

                    post.done(function (data) {
                        var template = $J("#contributors-template").html();

                        if (data.SkinnyContributorPages) {
                            var result = Mustache.to_html(template, data);

                            $J(tileContainer).append(result);

                            canonHelper.tileMarginFix($J(tileContainer));
                        }

                        if (data && data.IsNextPageAvailable) {
                            var loadMoreText = "<span>Load more " + data.TilesTypeForLoadMore + "</span><br>" + "(" + data.NextItemToDisplayed + ") " + data.TilesCounterForLoadMore + " left";
                            $J(loadMoreEl).html(loadMoreText);
                            $J(loadMoreEl).attr("data-current-page", data.CurrentPageIndex);
                            $J(loadMoreContainerEl).removeClass('hide--me');
                        } else {
                            if (!loadMoreContainerEl.hasClass('hide--me')) {
                                loadMoreContainerEl.addClass('hide--me');
                            }
                        }

                        canonHelper.hideSpinner();

                    });

                    post.fail(function () {
                        canonHelper.hideSpinner();
                    });

                    post.always(function () {
                        //$J('.load-more-feed button').prop('disabled', false).removeClass('loading');
                    });

                });
            },

            initDownloadResourceForm: function () {
                if ($J('.cp19').length > 0) {
                    function validateInputs() {
                        var isValid = true;
                        $('.cp19 .eloqua-ajax-frm').find('input').each(function () {
                            if ($(this).attr('required') == "required" && $(this).val().length < 1) {
                                isValid = false;
                                return;
                            }
                        });

                        return isValid;
                    }

                    function validateDropDown() {
                        var isValid = true;
                        $('.cp19 .eloqua-ajax-frm').find('select').each(function () {
                            if ($(this).attr('required') == "required" && $(this).prop('selectedIndex') < 1) {
                                isValid = false;
                                return;
                            }
                        });

                        return isValid;
                    }
                    var currentFormButton = $J('.cp19 .eloqua-ajax-frm button.eloqua-submit');
                    if (currentFormButton.length > 0) {
                        var ctaCopy = $J('.cp19 .cp19CtaCopy').val();
                        var isValid = true;
                        currentFormButton.text(ctaCopy);
                        currentFormButton.attr('disabled', '');
                        currentFormButton.addClass('disabled', '');
                        isValid = validateInputs() && validateDropDown();
                        if (isValid) {
                            currentFormButton.removeAttr('disabled');
                            currentFormButton.removeClass('disabled');
                        }
                        $('.cp19 .eloqua-ajax-frm input').change(function () {
                            if (validateInputs() && validateDropDown()) {
                                currentFormButton.removeAttr('disabled');
                                currentFormButton.removeClass('disabled');
                            }
                            else {
                                currentFormButton.attr('disabled', '');
                                currentFormButton.addClass('disabled', '');
                            }
                        });

                        $('.cp19 .eloqua-ajax-frm select').change(function () {
                            if (validateDropDown() && validateInputs()) {
                                currentFormButton.removeAttr('disabled');
                                currentFormButton.removeClass('disabled');
                            } else {
                                currentFormButton.attr('disabled', '');
                                currentFormButton.addClass('disabled', '');
                            }
                        });
                    }
                }
            },

            initDownloadResourceFormOnSubmit: function (currentForm) {
                if ($J(currentForm).closest(".cp19") != undefined && $J(currentForm).closest(".cp19").length > 0) {
                    canonHelper.setCookie("CANON_RESOURCE_FORM_SUBMITTED", "1", 1);
                    $J(currentForm).closest(".eloqua-container").addClass("hide--me");
                    canonHelper.showSpinner();
                    var responseData = $J.getJSON("/content-tile/fastbusiness/downloadresourcemediaitem?mediaitemid=" + $.trim($J(currentForm).closest(".cp19").data("media-id")));
                    responseData.done(function (data) {
                        if (data != undefined && data.ResourceMediaItemUrl != undefined && $.trim(data.ResourceMediaItemUrl) != "") {
                            $J(currentForm).closest(".cp19").find(".download-resource").attr("href", data.ResourceMediaItemUrl);
                            $J(currentForm).closest(".cp19").find(".download-resource").removeClass("hide--me");
                            var $a = $('<a />', {
                                'href': data.ResourceMediaItemUrl,
                                'text': "click",
                                'target': "_blank"
                            }).hide().appendTo("body")[0].click();
                        }
                        canonHelper.hideSpinner();
                    });

                    responseData.fail(function () {
                        $J(currentForm).closest(".cp19").find(".download-resource").hide();
                        canonHelper.hideSpinner();
                    });
                    if ($J(currentForm).closest(".cp19") && $J(currentForm).closest(".cp19").offset() != undefined && $J(currentForm).closest(".cp19").offset().top != undefined) {
                        $('html, body').animate({
                            scrollTop: $J(currentForm).closest(".cp19").offset().top - $J(currentForm).closest(".eloqua-container").height() - 70
                        }, 1000);
                    }
                }
            }

        };

        return _fastBusinessScope;

    })();

    $J(document).ready(function () {
        if (canonHelper !== undefined) {
            fastBusiness.init();
        }
    });
})(jQuery);;
(function ($J) {
    var myCanonBusiness = (function () {
        var _myCanonBusinessScope = {
            init: function () {
                this.initMyCanonBusinessDeviceIssues();
                this.initMyCanonBusinessDashboardDeviceIssues();
                //this.inityCanonBusinessDeviceLocations();
            },

            inityCanonBusinessDeviceLocations: function () {
                if (typeof (mcbDevices) !== "undefined" && mcbDevices != null) {
                    $(mcbDevices).each(function (i, o) {
                        o.address = "retrieving address......";

                        var get = $J.get('/canonhub/mycanonbusiness/FetchDeviceDetails?serialNumber=' + o.serial);

                        get.done(function (data) {

                            if (data == null) return;

                            o.address = getDeviceAddress(data.InstallAddress);
                        });
                    });
                }

                function getDeviceAddress(installAddress) {
                    var address = "";

                    if (installAddress.AddressLine1 != null)
                        address += installAddress.AddressLine1;

                    if (installAddress.AddressLine2 != null)
                        address += " " + installAddress.AddressLine2;

                    if (installAddress.AddressLine3 != null)
                        address += " " + installAddress.AddressLine3;

                    if (installAddress.AddressLine4 != null)
                        address += " " + installAddress.AddressLine4;

                    if (installAddress.Suburb != null)
                        address += " " + installAddress.Suburb;

                    if (installAddress.Postcode != null)
                        address += " " + installAddress.Postcode;

                    if (installAddress.State != null)
                        address += " " + installAddress.State;

                    return address;
                }
            },
            
            initMyCanonBusinessDeviceIssues: function () {
                var synchedDevices = [];
                var lastIndexRead = -1;
                var devicesHaveIssues = 1;
                var backgroundTask = {};
                var $scope = $J('.mcb2--dash__devices');
                if ($scope && $scope.length > 0) {
                    var devicePerRequest = parseInt($scope.attr('data-device-perrequest'));
                    backgroundTask = setInterval(syncDeviceIssue, 500);
                }

                function syncDeviceIssue() {
                    var postData = {
                        deviceSerial: []
                    };

                    if (lastIndexRead == (mcbDevices.length - 1)) {
                        clearInterval(backgroundTask);
                        return;
                    }

                    if(lastIndexRead == -1){
                        lastIndexRead = 0;
                    }

                    var counter = 0;
                    var indexStartFrom = lastIndexRead != 0 ? lastIndexRead + 1 : lastIndexRead;
                    for (var index = indexStartFrom; index < mcbDevices.length; index++) {
                        counter++;
                        if (counter <= devicePerRequest) {
                            lastIndexRead = index;
                            postData.deviceSerial.push(mcbDevices[index].serial);
                        }
                        else {
                            break;
                        }
                    }

                    if (postData.deviceSerial.length > 0) {
                        var data = canonHelper.addAntiForgeryToken(postData);
                        var post = $J.post('/canonhub/mycanonbusiness/fetcherrorandjamhistory', data);

                        post.done(function (data) {
                            canonHelper.hideSpinner();
                            if (data) {

                                for (var index = 0; index < data.length; index++) {
                                    var dataIndex = -1;
                                    var existingData = $J.grep(mcbDevices, function (n, i) {
                                        if (n.serial === data[index].serial) {
                                            dataIndex = i;
                                        }
                                    });

                                    var isError = data[index].issue && data[index].issue.IssueType === "error";
                                    var isPaperJam = data[index].issue && data[index].issue.IssueType === "jam";

                                    var status = isError ? "3" : isPaperJam ? "2" : "0";
                                    var statusDescription = data[index].issue && (isError || isPaperJam) ? data[index].issue.Description : "Ok";

                                    if (dataIndex !== -1) {
                                        mcbDevices[dataIndex].status = status;
                                        mcbDevices[dataIndex].statusError = statusDescription;
                                        if (status != 0) {
                                            $("#supportdevicesCount").html(devicesHaveIssues);
                                            devicesHaveIssues++;
                                        }
                                    }
                                }
                            }
                        });

                        post.fail(function (ex) {

                        });
                    }
                }
            },
            
            initMyCanonBusinessDashboardDeviceIssues: function () {
                $(".mcb2--dashboard__devices").css("display", "block");
                $(".business-image-spinner").css("display", "block");
                var lastIndexRead = 0;
                var displayDevicesCount = 0;
                var backgroundTask = {};
                var backgroundTaskRequestConter = {};
                var $scope = $J('.mcb2--dashboard__devices');
                if ($scope && $scope.length > 0) {
                    var devicePerRequest = parseInt($scope.attr('data-device-perrequest'));
                    backgroundTask = setInterval(syncDashboardDeviceIssue, 500);
                    backgroundTaskRequestConter = setInterval(checkRequestCounter,500);
                }

                function checkRequestCounter() {
                    if (mcbDashboardDevicesCounter === 0) {
                        $(".business-image-spinner").css("display", "none");
                        clearInterval(backgroundTaskRequestConter);
                        if($('.mcb2--dashboard__devices .mcb03:not(".hide--me")').length == 0){
                            var $noDeviceWithIssueContainer = $('.no-issue-on-devices');
                            if($noDeviceWithIssueContainer && $($noDeviceWithIssueContainer).length > 0){
                                $J($noDeviceWithIssueContainer).removeClass('hide--me');
                            }
                        }
                    }
                }

                function syncDashboardDeviceIssue() {
                    var postData = {
                        deviceSerial: []
                    };

                    if (lastIndexRead == (mcbDashboardDevices.length - 1)) {
                        clearInterval(backgroundTask);
                        return;
                    }
                    var counter = 0;
                    var indexStartFrom = lastIndexRead != 0 ? lastIndexRead + 1 : lastIndexRead;
                    for (var index = indexStartFrom; index < mcbDashboardDevices.length; index++) {
                        counter++;
                        if (counter <= devicePerRequest) {
                            lastIndexRead = index;
                            postData.deviceSerial.push(mcbDashboardDevices[index].serial);
                        }
                        else {
                            break;
                        }
                    }
                    if (postData.deviceSerial.length > 0) {
                        mcbDashboardDevicesCounter++;
                        $(".business-image-spinner").css("display", "block");
                        var data = canonHelper.addAntiForgeryToken(postData);
                        var post = $J.post('/canonhub/mycanonbusiness/fetcherrorandjamhistory', data);

                        post.done(function (data) {
                            mcbDashboardDevicesCounter--;
                            if (data) {
                                for (var index = 0; index < data.length; index++) {
                                    var dataIndex = -1;
                                    var existingData = $J.grep(mcbDashboardDevices, function (n, i) {
                                        if (n.serial === data[index].serial) {
                                            dataIndex = i;
                                        }
                                    });

                                    var isError = data[index].issue && data[index].issue.IssueType === "error";
                                    var isPaperJam = data[index].issue && data[index].issue.IssueType === "jam";

                                    var status = isError ? "3" : isPaperJam ? "2" : "0";
                                    if (status != 0) {
                                        $(".mcb03[data-attr-serial='" + data[index].serial + "']").removeClass("hide--me");
                                        if (status == "3") {
                                            $(".mcb03[data-attr-serial='" + data[index].serial + "'] .error").removeClass("hide--me");
                                        } else if (status == "2") {
                                            $(".mcb03[data-attr-serial='" + data[index].serial + "'] .jam").removeClass("hide--me");
                                        }
                                        displayDevicesCount++;
                                        $(".mydevices-counter").html(displayDevicesCount);
                                    }
                                }
                            }
                        });

                        post.fail(function (ex) {
                            mcbDashboardDevicesCounter--;
                        });
                    }
                }
            }
        };

        return _myCanonBusinessScope;

    })();

    $J(document).ready(function () {
        if (canonHelper !== undefined) {
            myCanonBusiness.init();
        }
    });
})(jQuery);;
(function ($J) {
    var relocationForm = (function () {
        var _relocationForm = {
            form: {},
            deviceSelector: {},
            addMoreDeviceButton: {},
            removeDeviceButton: {},
            selectedDeviceSerialNumbers: {},
            serialNumbers: [],
            init: function () {
                _relocationForm.form = $J('.form-relocation-form-v2');
                if (_relocationForm.form && _relocationForm.form.length > 0) {
                    this.initRelocationForm();
                }
            },

            initRelocationForm: function () {
                _relocationForm.deviceSelector = _relocationForm.form.find('.serial-number-selector');
                _relocationForm.addMoreDeviceButton = _relocationForm.form.find('.add-device');
                _relocationForm.removeDeviceButton = _relocationForm.form.find('.remove-selected-device');
                _relocationForm.selectedDeviceSerialNumbers = _relocationForm.form.find('#selected-device-serialnumbers');

                if (_relocationForm.deviceSelector && _relocationForm.deviceSelector.length > 0) {
                    _relocationForm.bindSerialNumberTypeAhead();
                }

                if (_relocationForm.addMoreDeviceButton && _relocationForm.addMoreDeviceButton.length > 0) {
                    $J(_relocationForm.addMoreDeviceButton).on('click', function (e) {
                        e.preventDefault();
                        _relocationForm.addMoreDevice($J(this));
                    });
                }

                if (_relocationForm.removeDeviceButton && _relocationForm.removeDeviceButton.length > 0) {
                    $J(_relocationForm.removeDeviceButton).on('click', function (e) {
                        e.preventDefault();
                        _relocationForm.removeDevice($J(this));
                    });
                }

                _relocationForm.form.find('input[mandatory="true"], select[mandatory="true"]').on('blur', function () {
                    if ($J(this).valid()) {
                        $J(this).closest('.field').find('span.error').text('');
                        $J(this).closest('.field').find('label.error').remove();
                    }
                })

                _relocationForm.form.find('input[mandatory="true"], select[mandatory="true"]').on('change', function () {
                    if ($J(this).valid()) {
                        $J(this).closest('.field').find('span.error').text('');
                        $J(this).closest('.field').find('label.error').remove();
                    }
                })
				
				var submitEl = _relocationForm.form.find('input[type="submit"]');
				if ( submitEl && submitEl.length > 0) {
                    $J(submitEl).off('click');
                    $J(submitEl).on('click', function (e) {
                        e.preventDefault();

                        canonHelper.showSpinner();
                        var selectedSerialNumbers = _relocationForm.form.find('#selected-device-serialnumbers').val();

                        if(selectedSerialNumbers && selectedSerialNumbers.length > 1){
                            _relocationForm.form.find('.serial-number-selector')[0].setCustomValidity('');
                            _relocationForm.form.find('.serial-number-selector').removeClass('error');
                            _relocationForm.form.find('.serial-number-selector-container span.error').addClass('hide--me');
                        }
                        else{
                            _relocationForm.form.find('.serial-number-selector')[0].setCustomValidity('Please specify your device');
                            _relocationForm.form.find('.serial-number-selector').addClass('error');
                            _relocationForm.form.find('.serial-number-selector-container span.error').removeClass('hide--me');
                        }

						var isValid = _relocationForm.form.valid() && selectedSerialNumbers && selectedSerialNumbers.length > 1;
						if (!isValid) {
                            canonHelper.hideSpinner();

                            _relocationForm.form.find("input[type!='hidden'].error").first().focus();
                            _relocationForm.form.find("input.error").each(function () {
                                var errorLabelText = $J(this).closest('.field').find('label.error').text();
                                $J(this).closest('.field').find('span.error').text(errorLabelText);
                            });

                            _relocationForm.form.find('#agreement').removeClass('error');
                        }
                        else{
                            _relocationForm.form.submit();
                        }
                    });
                }

                _relocationForm.initPickUpContact();
                _relocationForm.initDeliveryContact();
                _relocationForm.initSameAddressAsPickupOption();
                _relocationForm.initDatePicker();
                _relocationForm.initHardDriveEraseRequiredOption();
            },

            initDatePicker: function () {
                var datePickers = _relocationForm.form.find("#datepicker");
                if (datePickers && datePickers.length > 0) {

                    var dateToday = new Date();
                    var newdate = new Date(dateToday);

                    newdate.setDate(newdate.getDate() + 5);

                    datePickers.datepicker('destroy');
                    datePickers.removeClass('hasDatepicker');
                    datePickers.datepicker({
                        showOn: "both",
                        buttonImage: "/images/svg/icon-datepicker.svg",
                        buttonImageOnly: !0,
                        buttonText: "Select date",
                        dateFormat: "dd/mm/yy",
                        minDate: newdate
                    });
                }
            },

            bindSerialNumberTypeAhead: function () {
                _relocationForm.form.find('.selected-device-to-move li').each(function () {
                    var serialNumber = $J(this).attr("data-serial");
                    _relocationForm.serialNumbers.push(serialNumber);
                });

                $J(_relocationForm.deviceSelector).on('change', function () {
                    _relocationForm.selectingDevice($J(this).val());
                });

                $J(_relocationForm.deviceSelector).typeahead({
                    minLength: 3,
                    source: _relocationForm.serialNumbers
                }).on('change', function () {
                    _relocationForm.selectingDevice($J(this).val());
                });
            },

            validateSerialNumber: function (value) {
                return ($J.inArray(value, _relocationForm.serialNumbers) !== -1);
            },

            selectingDevice: function (deviceSerialNumber) {
                if (_relocationForm.validateSerialNumber(deviceSerialNumber)) {
                    var selectedDeviceList = _relocationForm.form.find('.selected-device-to-move li[data-serial="' + deviceSerialNumber + '"]');
                    if (selectedDeviceList && selectedDeviceList.length > 0 && selectedDeviceList.hasClass('hide--me')) {
                        _relocationForm.addMoreDeviceButton.removeAttr('disabled');

                        var listAvailableDevice = _relocationForm.form.find('.selected-device-to-move li[data-serial="' + deviceSerialNumber + '"]');
                        if (listAvailableDevice && listAvailableDevice.length > 0) {
                            var availableDeviceImage = listAvailableDevice.find('img');
                            if (availableDeviceImage && availableDeviceImage.length > 0 && availableDeviceImage.attr('src')) {
                                var deviceImage = _relocationForm.form.find('.selected-device-to-add img');
                                if (deviceImage && deviceImage.length > 0) {
                                    deviceImage.removeClass('hide--me');
                                    deviceImage.attr('src', availableDeviceImage.attr('src'));
                                }
                            }

                            var availableDeviceModel = listAvailableDevice.find('h3');
                            if (availableDeviceModel && availableDeviceModel.length > 0 && availableDeviceModel.text()) {
                                var deviceModel = _relocationForm.form.find('.selected-device-to-add h3');
                                if (deviceModel && deviceModel.length > 0) {
                                    deviceModel.removeClass('hide--me');
                                    deviceModel.text(availableDeviceModel.text());
                                }
                            }
                        }
                    }
                }
                else {
                    _relocationForm.addMoreDeviceButton.attr('disabled', '');
                }
            },

            removeDevice: function (el) {
                var currentDeviceListItem = $J(el).parent();
                var serialNumber = currentDeviceListItem.attr("data-serial");

                var currentSelectedSerialNumbers = _relocationForm.selectedDeviceSerialNumbers.val();
                currentSelectedSerialNumbers = currentSelectedSerialNumbers.replace("," + serialNumber, "");
                currentSelectedSerialNumbers = currentSelectedSerialNumbers.replace(serialNumber, "");
                _relocationForm.selectedDeviceSerialNumbers.val(currentSelectedSerialNumbers);

                currentDeviceListItem.addClass('hide--me');

                var counter = _relocationForm.form.find('.selected-device-to-move li').not('.hide--me').length;
                if (counter === 0) {
                    var listAvailableDeviceContainer = currentDeviceListItem.closest('.selected-device-to-move');
                    listAvailableDeviceContainer.addClass('hide--me');
                }

                _relocationForm.form.find(".serial-number-selector").val('');
            },

            addMoreDevice: function (el) {
                el.attr('disabled', 'disabled');
                var serialNumberSelectorEl = _relocationForm.form.find(".serial-number-selector");
                var selectedDeviceSerialNumber = serialNumberSelectorEl.val();
                var currentSelectedSerialNumbers = _relocationForm.selectedDeviceSerialNumbers.val();

                 var listAvailableDevice = _relocationForm.form.find('.selected-device-to-move li[data-serial="' + selectedDeviceSerialNumber + '"]');

                var listAvailableDeviceContainer = listAvailableDevice.closest('.selected-device-to-move');
                listAvailableDeviceContainer.removeClass('hide--me');
                listAvailableDevice.removeClass('hide--me');
                serialNumberSelectorEl.val('');

                _relocationForm.form.find('.serial-number-selector').removeClass('error');
                _relocationForm.form.find('.serial-number-selector-container span.error').addClass('hide--me');

                if (currentSelectedSerialNumbers.length == 0) {
                    canonHelper.showSpinner();

                    var get = $J.get('/canonhub/mycanonbusiness/FetchDeviceDetails?serialNumber=' + selectedDeviceSerialNumber);

                    get.done(function (data) {

                        if (data == null) return;

                        _relocationForm.form.find('#pickup-location-address1').val(data.InstallAddress.AddressLine1).change();
                        _relocationForm.form.find('#pickup-location-address2').val(data.InstallAddress.AddressLine2).change();
                        _relocationForm.form.find('#pickup-location-suburb').val(data.InstallAddress.Suburb).change();
                        _relocationForm.form.find('#pickup-location-state').val(data.InstallAddress.State).change();
                        _relocationForm.form.find('#pickup-location-postcode').val(data.InstallAddress.Postcode).change();

                        canonHelper.hideSpinner();
                    });

                    get.fail(function (ex) {
                        canonHelper.hideSpinner();
                    });
                }

                if (currentSelectedSerialNumbers.length > 0) {
                    _relocationForm.selectedDeviceSerialNumbers.val("," + selectedDeviceSerialNumber);
                }
                else {
                    _relocationForm.selectedDeviceSerialNumbers.val(selectedDeviceSerialNumber);
                }
            },

            initSameAddressAsPickupOption: function () {
                var sameAsPickupLocationContainer = _relocationForm.form.find('.same-as-pickup-location-container');
                if (sameAsPickupLocationContainer && sameAsPickupLocationContainer.length > 0) {
                    var newDeliveryLocation = _relocationForm.form.find('.diff-moving-to-address');
                    var isSameAddressAsPickupLocationEl = _relocationForm.form.find('#IsSameAddressAsPickupLocation');
                    sameAsPickupLocationContainer.find('#IsSameMovingToAddress-yes').off('click');
                    sameAsPickupLocationContainer.find('#IsSameMovingToAddress-yes').on('click', function () {
                        if (newDeliveryLocation && newDeliveryLocation.length > 0) {
                            newDeliveryLocation.show();
                            newDeliveryLocation.find('input[mandatory]').attr('required', '');
                        }

                        if (isSameAddressAsPickupLocationEl && isSameAddressAsPickupLocationEl.length > 0) {
                            isSameAddressAsPickupLocationEl.val('true');
                        }
                    });
					
					newDeliveryLocation.hide();
                    newDeliveryLocation.find('input[mandatory]').removeAttr('required');

                    sameAsPickupLocationContainer.find('#IsSameMovingToAddress-no').off('click');
                    sameAsPickupLocationContainer.find('#IsSameMovingToAddress-no').on('click', function () {
                        if (newDeliveryLocation && newDeliveryLocation.length > 0) {
                            newDeliveryLocation.hide();
                            newDeliveryLocation.find('input[mandatory]').removeAttr('required');
                        }

                        if (isSameAddressAsPickupLocationEl && isSameAddressAsPickupLocationEl.length > 0) {
                            isSameAddressAsPickupLocationEl.val('false');
                        }
                    });
                }
            },

            initPickUpContact: function () {
                var pickupContactContainer = _relocationForm.form.find('.pickup-different-contact');
                if (pickupContactContainer && pickupContactContainer.length > 0) {
                    var isPickupHasDifferentContactEl = _relocationForm.form.find('#IsPickupHasDifferentContact');
					
					pickupContactContainer.addClass('hide--me');
                    isPickupHasDifferentContactEl.val('false');
                    pickupContactContainer.find('#pickup-contact-name').removeAttr('required');
						
                    _relocationForm.form.find('#extra-contact-pickup-yes').on('change', function () {
                        pickupContactContainer.removeClass('hide--me');
                        pickupContactContainer.find('#pickup-contact-name').attr('required', '');
                        isPickupHasDifferentContactEl.val('true');
                    });

                    _relocationForm.form.find('#extra-contact-pickup-no').on('change', function () {
                        pickupContactContainer.addClass('hide--me');
                        isPickupHasDifferentContactEl.val('false');
                        pickupContactContainer.find('#pickup-contact-name').removeAttr('required');
                    });
                }
            },

            initDeliveryContact: function () {
                var deliveryContactContainer = _relocationForm.form.find('.delivery-different-contact');
                if (deliveryContactContainer && deliveryContactContainer.length > 0) {
                    var isDeliveryHasDifferentContactEl = _relocationForm.form.find('#IsDeliveryHasDifferentContact');
                    
					deliveryContactContainer.addClass('hide--me');
                    isDeliveryHasDifferentContactEl.val('false');
                    deliveryContactContainer.find('#delivery-contact-name').removeAttr('required');
					
					_relocationForm.form.find('#extra-contact-delivery-yes').on('change', function () {
                        deliveryContactContainer.removeClass('hide--me');
                        isDeliveryHasDifferentContactEl.val('true');
                        deliveryContactContainer.find('#delivery-contact-name').attr('required', '');
                    });

                    _relocationForm.form.find('#extra-contact-delivery-no').on('change', function () {
                        deliveryContactContainer.addClass('hide--me');
                        isDeliveryHasDifferentContactEl.val('false');
                        deliveryContactContainer.find('#delivery-contact-name').removeAttr('required');
                    });
                }
            },

            initHardDriveEraseRequiredOption: function () {
                var isHardDriveEraseRequiredEl = _relocationForm.form.find('#IsHardDriveEraseRequired');

                _relocationForm.form.find('#IsHardDriveEraseRequired-yes').on('change', function() {
                    if (isHardDriveEraseRequiredEl && isHardDriveEraseRequiredEl.length > 0) {
                        isHardDriveEraseRequiredEl.val('true');
                    }
                });

                _relocationForm.form.find('#IsHardDriveEraseRequired-no').on('change', function () {
                    if (isHardDriveEraseRequiredEl && isHardDriveEraseRequiredEl.length > 0) {
                        isHardDriveEraseRequiredEl.val('false');
                    }
                });
            }
        };

        return _relocationForm;

    })();

    $J(document).ready(function () {
        if (canonHelper !== undefined) {
            relocationForm.init();
        }
    });
})(jQuery);;
(function ($J) {
    var nzRelocationForm = (function () {
        var _nzRelocationForm = {
            form: {},
            deviceSelector: {},
            addMoreDeviceButton: {},
            removeDeviceButton: {},
            selectedDeviceSerialNumbers: {},
            page1Container: {},
            page2Container: {},
            page3Container: {},
            serialNumbers: [],
            init: function () {
                _nzRelocationForm.form = $J('form.nz-relocation-form');
                if (_nzRelocationForm.form && _nzRelocationForm.form.length > 0) {
                    this.initRelocationForm();
                }
            },

            initRelocationForm: function () {
                _nzRelocationForm.page1Container = _nzRelocationForm.form.find('.nz-relocation-form-page1');
                _nzRelocationForm.page2Container = _nzRelocationForm.form.find('.nz-relocation-form-page2');
                _nzRelocationForm.page3Container = _nzRelocationForm.form.find('.nz-relocation-form-page3');

                _nzRelocationForm.deviceSelector = _nzRelocationForm.form.find('.product-model-search-box');
                _nzRelocationForm.addMoreDeviceButton = _nzRelocationForm.form.find('.add-device');
                _nzRelocationForm.removeDeviceButton = _nzRelocationForm.form.find('.remove-selected-device');
                _nzRelocationForm.selectedDeviceSerialNumbers = _nzRelocationForm.form.find('#selected-device-serialnumbers');

                _nzRelocationForm.bindProductNameTypeAhead();
                _nzRelocationForm.initAddMoreDevice();

                _nzRelocationForm.form.find('input[mandatory="true"], select[mandatory="true"]').attr('required', '');

                if (_nzRelocationForm.addMoreDeviceButton && _nzRelocationForm.addMoreDeviceButton.length > 0) {
                    $J(_nzRelocationForm.addMoreDeviceButton).on('click', function (e) {
                        e.preventDefault();
                        _nzRelocationForm.addMoreDevice($J(this));
                    });
                }

                if (_nzRelocationForm.removeDeviceButton && _nzRelocationForm.removeDeviceButton.length > 0) {
                    $J(_nzRelocationForm.removeDeviceButton).on('click', function (e) {
                        e.preventDefault();
                        _nzRelocationForm.removeDevice($J(this));
                    });
                }

                _nzRelocationForm.initDatePicker();
                _nzRelocationForm.initFormStepButton();
            },

            initFormStepButton: function () {
                _nzRelocationForm.form.find('.go-to-page-1').on('click', function () {
                    _nzRelocationForm.page1Container.removeClass('hide--me');

                    if (!_nzRelocationForm.page2Container.hasClass('hide--me')) {
                        _nzRelocationForm.page2Container.addClass('hide--me');
                    }

                    if (!_nzRelocationForm.page3Container.hasClass('hide--me')) {
                        _nzRelocationForm.page3Container.addClass('hide--me');
                    }

                    _nzRelocationForm.scrollToTop();

                });

                _nzRelocationForm.form.find('input[mandatory="true"]').on('blur', function () {
                    if ($J(this).valid()) {
                        $J(this).closest('.field').find('span.error').text('');
                        $J(this).closest('.field').find('label.error').remove();
                    }
                })

                _nzRelocationForm.form.find('input[mandatory="true"]').on('change', function () {
                    if ($J(this).valid()) {
                        $J(this).closest('.field').find('span.error').text('');
                        $J(this).closest('.field').find('label.error').remove();
                    }
                })

                _nzRelocationForm.form.find('.go-to-page-1').on('click', function (e) {
                    e.preventDefault();
                    e.stopPropagation();

                    if (!_nzRelocationForm.page2Container.hasClass('hide--me')) {
                        _nzRelocationForm.page2Container.addClass('hide--me');
                    }

                    if (!_nzRelocationForm.page3Container.hasClass('hide--me')) {
                        _nzRelocationForm.page3Container.addClass('hide--me');
                    }

                    _nzRelocationForm.page1Container.removeClass('hide--me');

                    _nzRelocationForm.form.find('.step-indicator li').removeClass('active');
                    _nzRelocationForm.form.find('.step-indicator li:first-child').addClass('active');
                    _nzRelocationForm.form.find('.step-indicator li a').attr('disabled', '');

                    if ($J(this).attr('data-scrolltop') === 'true') {
                        _nzRelocationForm.scrollToTop();
                    }

                });

                _nzRelocationForm.form.find('.go-to-page-2').on('click', function (e) {
                    e.preventDefault();
                    e.stopPropagation();

                    var isValid = _nzRelocationForm.page1Container.find("input[mandatory], select[mandatory]").valid();
                    if (isValid) {
                        if (!_nzRelocationForm.page1Container.hasClass('hide--me')) {
                            _nzRelocationForm.page1Container.addClass('hide--me');
                        }

                        _nzRelocationForm.page2Container.removeClass('hide--me');

                        if (!_nzRelocationForm.page3Container.hasClass('hide--me')) {
                            _nzRelocationForm.page3Container.addClass('hide--me');
                        }

                        _nzRelocationForm.form.find('.step-indicator li').removeClass('active');
                        _nzRelocationForm.form.find('.step-indicator li:nth-child(2)').addClass('active');
                        _nzRelocationForm.form.find('.step-indicator li:first-child a').removeAttr('disabled');

                        if ($J(this).attr('data-scrolltop') === 'true') {
                            _nzRelocationForm.scrollToTop();
                        }

                    } else {
                        _nzRelocationForm.form.find("input.error").first().focus();
                        _nzRelocationForm.form.find("input.error").each(function () {
                            var errorLabelText = $J(this).closest('.field').find('label.error').text();
                            $J(this).closest('.field').find('span.error').text(errorLabelText);
                        });

                        var datePickerErrorEl= _nzRelocationForm.form.find("input.dpicker.error, input[type='time'].error");
                        if(datePickerErrorEl && datePickerErrorEl.length > 0){
                            datePickerErrorEl.closest('.row').find('span.error').text('Relocation only available between 8-5pm');
                        }
                    }
                });

                _nzRelocationForm.form.find('.go-to-page-3').on('click', function (e) {
                    e.preventDefault();
                    e.stopPropagation();

                    var isValid = _nzRelocationForm.page2Container.find("input[mandatory], select[mandatory]").valid();
                    if (isValid) {
                        if (!_nzRelocationForm.page1Container.hasClass('hide--me')) {
                            _nzRelocationForm.page1Container.addClass('hide--me');
                        }

                        if (!_nzRelocationForm.page2Container.hasClass('hide--me')) {
                            _nzRelocationForm.page2Container.addClass('hide--me');
                        }

                        _nzRelocationForm.page3Container.removeClass('hide--me');

                        _nzRelocationForm.form.find('.step-indicator li').removeClass('active');
                        _nzRelocationForm.form.find('.step-indicator li:last-child').addClass('active');
                        _nzRelocationForm.form.find('.step-indicator li:first-child a').removeAttr('disabled');
                        _nzRelocationForm.form.find('.step-indicator li:nth-child(2) a').removeAttr('disabled');

                        if ($J(this).attr('data-scrolltop') === 'true') {
                            _nzRelocationForm.scrollToTop();
                        }
                    }
                    else {
                        _nzRelocationForm.form.find("input.error").first().focus();
                        _nzRelocationForm.form.find("input.error").each(function () {
                            var errorLabelText = $J(this).closest('.field').find('label.error').text();
                            $J(this).closest('.field').find('span.error').text(errorLabelText);
                        });

                        var datePickerErrorEl= _nzRelocationForm.form.find("input.dpicker.error, input[type='time'].error");
                        if(datePickerErrorEl && datePickerErrorEl.length > 0){
                            datePickerErrorEl.closest('.row').find('span.error').text('Relocation only available between 8-5pm');
                        }
                    }
                });

                _nzRelocationForm.form.find('input[type="submit"]').on('click', function (e) {
                    canonHelper.showSpinner();
					var isValid = _nzRelocationForm.form.valid();
                    if (!isValid) {
						canonHelper.hideSpinner();
                        _nzRelocationForm.form.find("input.error").first().focus();
                        _nzRelocationForm.form.find("input.error").each(function () {
                            var errorLabelText = $J(this).closest('.field').find('label.error').text();
                            $J(this).closest('.field').find('span.error').text(errorLabelText);
                        });
                    }
                });
            },

            initAddMoreDevice: function () {

                var fieldContainerEl = _nzRelocationForm.form.find(".devices .field");
                var addMoreDeviceEl = _nzRelocationForm.form.find(".nz-add-more-device");

                var addNewMachineRows = function addRow(field) {
                    var index = parseInt($J(addMoreDeviceEl).data("noofdevices")) + 1;
                    if (index < 10) {
                        $J(addMoreDeviceEl).data("noofdevices", index);
                        //copy the table row and clear the value of the input, then append the row to the end of the table
                        $("." + field + " .field:first").clone().find("input").each(function () {
                            $(this).val("");
                            $(this).attr("id", $(this).attr("id") + index);
                        }).end().appendTo("." + field);

                        $("." + field + " .field:nth-child(2)").clone().find("input").each(function () {
                            $(this).val("");
                            $(this).attr("id", $(this).attr("id") + index);
                        }).end().appendTo("." + field);

                        //Remove device
                        $("." + field + " .field:nth-child(3)").clone().find("a").each(function () {
                            $(this).attr("id", $(this).attr("id") + index);
                            $(this).show();
                            $(this).click(function () {
                                var counter = $J(addMoreDeviceEl).data("noofdevices");
                                $J(addMoreDeviceEl).data("noofdevices", counter - 1);
                                _nzRelocationForm.form.find("#product-name" + index).parent().remove();
                                _nzRelocationForm.form.find("#product-serial" + index).parent().remove();
                                _nzRelocationForm.form.find("#nz-remove-device" + index).parent().remove();
                            });
                        }).end().appendTo("." + field);
                    }
                }

                if (addMoreDeviceEl && addMoreDeviceEl.length > 0) {
                    fieldContainerEl.find(".remove-more-device").hide();

                    addMoreDeviceEl.off('click');
                    addMoreDeviceEl.on('click', function (e) {
                        e.preventDefault();
                        e.stopPropagation();

                        addNewMachineRows("devices");
                    });
                }
            },

            scrollToTop: function () {
                $('html, body').animate({ scrollTop: 0 }, 1000);
            },

            initDatePicker: function () {
                var datePickers = _nzRelocationForm.form.find(".dpicker");
                if (datePickers && datePickers.length > 0) {

                    var dateToday = new Date();
                    var newdate = new Date(dateToday);

                    newdate.setDate(newdate.getDate() + 5);

                    datePickers.datepicker('destroy');
                    datePickers.removeClass('hasDatepicker');
                    datePickers.datepicker({
                        showOn: "both",
                        buttonImage: "/images/svg/icon-datepicker.svg",
                        buttonImageOnly: !0,
                        buttonText: "Select date",
                        dateFormat: "dd/mm/yy",
                        minDate: newdate
                    });
                }
            },

            bindProductNameTypeAhead: function () {

                if (_nzRelocationForm.deviceSelector && _nzRelocationForm.deviceSelector.length > 0) {
                    _nzRelocationForm.form.delegate('.product-model-search-box', 'focus', function () {
                        var currentProductModelSearchBoxEl = $J(this);

                        currentProductModelSearchBoxEl.typeahead({
                            source: $.debounce(function (query, process) {
                                typeaheadSource(query, process);
                            },300),
                            minLength: 3,
                            items: "8"
                        }).on('change', function () {
                            if ($J(this).val().length > 0) {
                                currentProductModelSearchBoxEl.val($J(this).val());
                                $J(this).closest('.field').find('span.error').text('');
                                $J(this).closest('.field').find('label.error').remove();
                            } else {
                                var errorLabelText = $J(this).closest('.field').find('label.error').text();
                                $J(this).closest('.field').find('span.error').text(errorLabelText);
                            }
                        });
                    });

                    function typeaheadSource(query, response) {
                        // This is going to make an HTTP post request to the controller3
                        canonHelper.showSpinner();
                        var post = $.post("/content/search/typeaheadforproduct", { query: query }, function (data) {
                            canonHelper.hideSpinner();
                            response(data);
                        }).fail(function () {
                            canonHelper.hideSpinner();
                        });

                        return post;
                    }
                }
            },

            removeDevice: function (el) {

            },

            addMoreDevice: function (el) {

            }
        };

        return _nzRelocationForm;

    })();

    $J(document).ready(function () {
        if (canonHelper !== undefined) {
            nzRelocationForm.init();
        }
    });
})(jQuery);;
(function ($J) {
    var sims = (function () {
        var _simsScope = {
            init: function () {
                this.initSIMSSearch();
                this.initSIMSFeedPaging();
                this.initSIMSContentPageEvents();
            },

            operatingSystemDetection: function () {
                //JavaScript Client Detection
                //(C) viazenetti GmbH (Christian Ludwig) http://jsfiddle.net/ChristianL/AVyND/

                // browser
                var appVersion = navigator.appVersion;
                var userAgent = navigator.userAgent;

                // system
                var os = window.unknown;
                var clientStrings = [
                    { s: 'Windows 10', r: /(Windows 10.0|Windows NT 10.0)/ },
                    { s: 'Windows 8.1', r: /(Windows 8.1|Windows NT 6.3)/ },
                    { s: 'Windows 8', r: /(Windows 8|Windows NT 6.2)/ },
                    { s: 'Windows 7', r: /(Windows 7|Windows NT 6.1)/ },
                    { s: 'Windows Vista', r: /Windows NT 6.0/ },
                    { s: 'Windows Server 2003', r: /Windows NT 5.2/ },
                    { s: 'Windows XP', r: /(Windows NT 5.1|Windows XP)/ },
                    { s: 'Windows 2000', r: /(Windows NT 5.0|Windows 2000)/ },
                    { s: 'Windows ME', r: /(Win 9x 4.90|Windows ME)/ },
                    { s: 'Windows 98', r: /(Windows 98|Win98)/ },
                    { s: 'Windows 95', r: /(Windows 95|Win95|Windows_95)/ },
                    { s: 'Windows NT 4.0', r: /(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)/ },
                    { s: 'Windows CE', r: /Windows CE/ },
                    { s: 'Windows 3.11', r: /Win16/ },
                    { s: 'Android', r: /Android/ },
                    { s: 'Open BSD', r: /OpenBSD/ },
                    { s: 'Sun OS', r: /SunOS/ },
                    { s: 'Linux', r: /(Linux|X11)/ },
                    { s: 'iOS', r: /(iPhone|iPad|iPod)/ },
                    { s: 'Mac OS X', r: /Mac OS X/ },
                    { s: 'Mac OS', r: /(MacPPC|MacIntel|Mac_PowerPC|Macintosh)/ },
                    { s: 'QNX', r: /QNX/ },
                    { s: 'UNIX', r: /UNIX/ },
                    { s: 'BeOS', r: /BeOS/ },
                    { s: 'OS/2', r: /OS\/2/ },
                    { s: 'Search Bot', r: /(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/ }
                ];

                for (var id in clientStrings) {
                    if (clientStrings.hasOwnProperty(id)) {
                        var clientString = clientStrings[id];
                        if (clientString.r.test(userAgent)) {
                            os = clientString.s;
                            break;
                        }
                    }
                }

                var osVersion = window.unknown;
                var is64Bit = userAgent.indexOf("WOW64") !== -1 || userAgent.indexOf("Win64") !== -1 ||
                    userAgent.indexOf("x86_64") !== -1 || userAgent.indexOf("x86-64") !== -1 ||
                    userAgent.indexOf("Win64") !== -1 || userAgent.indexOf("x64;") !== -1 ||
                    userAgent.indexOf("amd64") !== -1 || userAgent.indexOf("AMD64") !== -1 ||
                    userAgent.indexOf("x64_64") !== -1 || userAgent.indexOf("ia64") !== -1 ||
                    userAgent.indexOf("sparc64") !== -1 || userAgent.indexOf("ppc64") !== -1 ||
                    userAgent.indexOf("IRIX64") !== -1;

                if (/Windows/.test(os)) {
                    osVersion = /Windows (.*)/.exec(os)[1];
                    os = 'Windows';
                }

                switch (os) {
                    case 'Mac OS X':
                        osVersion = /Mac OS X (10[\.\_\d]+)/.exec(userAgent)[1];
                        return {
                            os: 'Mac',
                            osVersion: osVersion,
                            fullOsText: os + " v" + osVersion.replace('_', '.'),
                            is64Bit: parseFloat(osVersion.replace('_', '.')) > 10.8
                        };
                    case 'Android':
                        osVersion = /Android ([\.\_\d]+)/.exec(userAgent)[1];
                        break;

                    case 'iOS':
                        osVersion = /OS (\d+)_(\d+)_?(\d+)?/.exec(appVersion);
                        osVersion = osVersion[1] + '.' + osVersion[2] + '.' + (osVersion[3] | 0);
                        break;
                }

                return {
                    os: os,
                    osVersion: osVersion,
                    fullOsText: is64Bit ? os + " " + osVersion + " x64" : os + " " + osVersion,
                    is64Bit: is64Bit
                };
            },

            initSIMSSearch: function () {
                if ($J('.cf05v2').length > 0) {

                    function autoDetectOsAndStartFetchTheData() {
                        var currentOs = _simsScope.operatingSystemDetection();

                        var mobile = canonHelper.isMobile();
                        if (!mobile) {
                            var osCategoryFilter = $J('.cf05v2').find('.os li[data-os-code="' + currentOs.os.toLowerCase() + '"]');
                            if (osCategoryFilter.length > 0) {
                                var osVersionFound = false;
                                var lastOptionOsVersion = $J('.cf05v2').find('select.download-os-version option:last').attr('value');

                                var categoryContainer = $J('.cf05v2').find('.category.desktop');
                                $J(categoryContainer).find('select.download-os-version option:not(.default)').remove();

                                var osVersions = $J(osCategoryFilter).attr('data-os-versions');
                                var osVersionsSelectEl = $J(categoryContainer).find('select.download-os-version');
                                var versions = osVersions.split(',');

                                $J.each(versions, function (index) {
                                    var option = $('<option>', {
                                        value: versions[index].toLowerCase(),
                                        text: versions[index]
                                    });

                                    if (currentOs.os !== undefined) {
                                        $J(option).attr('data-os-code', currentOs.os.toLowerCase());
                                    }

                                    $J(osVersionsSelectEl).append($J(option));
                                });

                                $J('.cf05v2').find('select.download-os-version option').each(function () {
                                    var currentOptionValue = $J(this).attr('value');
                                    var optionValue = currentOptionValue.replace(/\s/g, '');
                                    if (currentOs.fullOsText.replace(/\s/g, '').toLowerCase() === optionValue.toLowerCase()) {
                                        $J('.cf05v2').find('.os li.active').removeClass('active');
                                        $J(osCategoryFilter).addClass('active');
                                        $J(this).parent().val(currentOptionValue);
                                        osVersionFound = true;
                                        $J(this).parent().trigger('change');
                                    }

                                    if (currentOptionValue === lastOptionOsVersion && !osVersionFound) {
                                        $J(osCategoryFilter).trigger('click');
                                    }
                                });
                            }
                        }
                    }

                    function resetFilters(tabContentContainer) {
                        $J(tabContentContainer).find(".category.desktop .os li.active").removeClass('active');
                        $J(tabContentContainer).find(".category.desktop .os li:first").addClass('active');

                        $J(tabContentContainer).find(".category.mobile .download-os-type option[selected]").removeAttr('selected');
                        $J(tabContentContainer).find(".category.mobile .download-os-type option:first").attr('selected', '');

                        $J(tabContentContainer).find(".category.mobile .download-os-version option[selected]").removeAttr('selected');
                        $J(tabContentContainer).find(".category.mobile .download-os-version option:first").attr('selected', '');

                        $J(tabContentContainer).find(".category.desktop .download-os-version option[selected]").removeAttr('selected');
                        $J(tabContentContainer).find(".category.desktop .download-os-version option:first").attr('selected', '');
                    }

                    function getSelectedOs() {
                        var tabContentContainer = $J('.tabcontent.active');
                        var selectedOsElement = {};
                        var selectedOs = '';

                        if (canonHelper.isMobile()) {
                            selectedOsElement = $J(tabContentContainer).find('.category.mobile select.download-os-type');
                            if ($J(selectedOsElement).length > 0) {
                                selectedOs = $J(selectedOsElement).val();
                            }
                        }
                        else {
                            selectedOsElement = $J(tabContentContainer).find('.category.desktop .os li.active');
                            if ($J(selectedOsElement).length > 0) {
                                selectedOs = $J(selectedOsElement).attr('data-os-code');
                            }
                        }

                        return selectedOs;
                    }

                    function getSelectedOsVersion() {
                        var tabContentContainer = $J('.tabcontent.active');

                        var selectedOsVersionElement = {};
                        var selectedOsVersion = '';

                        if (canonHelper.isMobile()) {
                            selectedOsVersionElement = $J(tabContentContainer).find('.category.mobile select.download-os-type');
                            if ($J(selectedOsVersionElement).length > 0) {
                                selectedOsVersion = $J(selectedOsVersionElement).val();
                            }

                            selectedOsVersionElement = $J(tabContentContainer).find('.category.mobile select.download-os-version');
                            if ($J(selectedOsVersionElement).length > 0) {
                                selectedOsVersion = $J(selectedOsVersionElement).val();
                            }
                        }
                        else {
                            selectedOsVersionElement = $J(tabContentContainer).find('.category.desktop .os li.active');
                            if ($J(selectedOsVersionElement).length > 0) {
                                selectedOsVersion = $J(selectedOsVersionElement).attr('data-os-code');
                            }

                            selectedOsVersionElement = $J(tabContentContainer).find('.category.desktop select.download-os-version');
                            if ($J(selectedOsVersionElement).length > 0) {
                                selectedOsVersion = $J(selectedOsVersionElement).val();
                            }
                        }

                        return selectedOsVersion;
                    }

                    function createOrUpdateStateElement() {

                        var tabContentContainer = $J('.tabcontent.active');

                        var selectedOs = getSelectedOs();
                        var selectedOsVersion = getSelectedOsVersion();

                        var stateElement = $J(tabContentContainer).find('.sims-search-state');
                        if ($J(stateElement).length > 0) {
                            $J(stateElement).attr("data-os-code", selectedOs);
                            $J(stateElement).attr("data-os-version", selectedOsVersion);
                        }
                        else {
                            stateElement = $J(document.createElement("input"));
                            $J(stateElement).attr("type", "hidden");
                            $J(stateElement).attr("name", "sims-search-state");
                            $J(stateElement).attr("class", "sims-search-state");

                            $J(stateElement).attr("data-os-code", selectedOs);
                            $J(stateElement).attr("data-os-version", selectedOsVersion);

                            $J(stateElement).attr("value", "canon");
                            $J(tabContentContainer).prepend(stateElement);
                        }
                    }

                    //Category and OS Version Mobile
                    $J('.cf05v2').on('click', '.category.mobile .update', function (e) {
                        var currentElement = $J(this);
                        var componentContainer = $J(currentElement).closest('.cf05v2');
                        var categoryContainer = $J(currentElement).closest('.category.mobile');

                        var selectedCategoryElement = $J(categoryContainer).find("select.download-os-type");
                        var selectedCategory = $J(selectedCategoryElement).val() !== 'all' ? $J(selectedCategoryElement).val() : '';
                        var selectedOsVersionElement = $J(categoryContainer).find('select.download-os-version');
                        var selectedOsVersion = $J(selectedOsVersionElement).val() !== 'all' ? $J(selectedOsVersionElement).val() : '';

                        var data = {
                            ProductSupportCategoryId: $J(componentContainer).attr('data-support-category'),
                            ProductId: $J(componentContainer).attr('data-product'),
                            AccessoryId: $J(componentContainer).attr('data-accessory'),
                            PageId: $J(componentContainer).attr('data-page'),
                            ModelId: $J(componentContainer).attr('data-model'),
                            ContentType: '',
                            FileType: '',
                            SelectedCategory: selectedCategory,
                            SelectedOsVersion: selectedOsVersion,
                            Keyword: '',
                            PageIndex: 0,
                            TabId: $J(componentContainer).find('.tabs-container li.active:visible').first().attr("data-tabid"),
                            IsDataSourced: $J(componentContainer).attr('data-isdatasourced')
                        };

                        currentElement.closest('.outer').find('.close').trigger('click');

                        var resultContainer = $(componentContainer).find('.tabcontent.active .sims-content-container');
                        _simsScope.getSIMSFeed(data, $J(componentContainer), resultContainer);
                    });

                    //Category desktop
                    $J('.cf05v2').on('click', '.category.desktop .os li', function (e) {
                        var currentElement = $J(this);
                        var categoryContainer = $J(currentElement).closest('.category.desktop');

                        $J(categoryContainer).find('select.download-os-version option:not(.default)').remove();

                        var osVersions = $J(currentElement).attr('data-os-versions');
                        var osVersionsSelectEl = $J(categoryContainer).find('select.download-os-version');
                        var versions = osVersions.split(',');

                        var componentContainer = $J(currentElement).closest('.cf05v2');

                        var keywordElement = $J(categoryContainer).find('.sims-search-feed');
                        $J(keywordElement).val('');

                        var selectedCategoryElement = $J(categoryContainer).find(".os li.active");
                        var selectedCategory = selectedCategoryElement != undefined && selectedCategoryElement.length > 0 ? $J(selectedCategoryElement).attr('data-os-code') : '';

                        $J.each(versions, function (index) {
                            var option = $('<option>', {
                                value: versions[index].toLowerCase(),
                                text: versions[index]
                            });

                            if (selectedCategory !== undefined) {
                                $J(option).attr('data-os-code', selectedCategory);
                            }

                            $J(osVersionsSelectEl).append($J(option));
                        });

                        var selectedOsVersionElement = $J(categoryContainer).find('select.download-os-version');
                        var selectedOsVersion = $J(selectedOsVersionElement).val() !== 'all' ? $J(selectedOsVersionElement).val() : '';

                        var data = {
                            ProductSupportCategoryId: $J(componentContainer).attr('data-support-category'),
                            ProductId: $J(componentContainer).attr('data-product'),
                            AccessoryId: $J(componentContainer).attr('data-accessory'),
                            PageId: $J(componentContainer).attr('data-page'),
                            ModelId: $J(componentContainer).attr('data-model'),
                            ContentType: '',
                            FileType: '',
                            SelectedCategory: selectedCategory,
                            SelectedOsVersion: selectedOsVersion,
                            Keyword: '',
                            PageIndex: 0,
                            TabId: $J(componentContainer).find('.tabs-container li.active:visible').first().attr("data-tabid"),
                            IsDataSourced: $J(componentContainer).attr('data-isdatasourced')
                        };

                        var resultContainer = $(componentContainer).find('.tabcontent.active .sims-content-container');
                        _simsScope.getSIMSFeed(data, $J(componentContainer), resultContainer);
                    });

                    //Category mobile
                    $J('.cf05v2').on('change', '.category.mobile .download-os-type', function (e) {
                        var currentElement = $J(this);
                        var categoryContainer = $J(currentElement).closest('.category.mobile');

                        $J(categoryContainer).find('select.download-os-version option:not(.default)').remove();

                        var os = $J($J(currentElement).find('option')[e.target.selectedIndex]).attr('data-os-code');
                        var osVersions = $J($J(currentElement).find('option')[e.target.selectedIndex]).attr('data-os-versions');
                        var osVersionsSelectEl = $J(categoryContainer).find('select.download-os-version');
                        var versions = osVersions.split(',');

                        $J.each(versions, function (index) {
                            var option = $('<option>', {
                                value: versions[index].toLowerCase(),
                                text: versions[index]
                            });

                            if (os !== undefined) {
                                $J(option).attr('data-os-code', os);
                            }

                            $J(osVersionsSelectEl).append($J(option));
                        });

                        var keywordElement = $J(categoryContainer).find('.sims-search-feed');
                        $J(keywordElement).val('');
                    });

                    //OS Version desktop
                    $J('.cf05v2').on('change', '.category.desktop .download-os-version', function (e) {
                        var currentElement = $J(this);
                        var componentContainer = $J(currentElement).closest('.cf05v2');
                        var categoryContainer = $J(currentElement).closest('.category.desktop');

                        var keywordElement = $J(categoryContainer).find('.sims-search-feed');
                        $J(keywordElement).val('');

                        var selectedCategoryElement = $J(categoryContainer).find(".os li.active");
                        var selectedCategory = selectedCategoryElement != undefined && selectedCategoryElement.length > 0 ? $J(selectedCategoryElement).attr('data-os-code') : '';
                        var selectedOsVersionElement = $J(categoryContainer).find('select.download-os-version');
                        var selectedOsVersion = $J(selectedOsVersionElement).val() !== 'all' ? $J(selectedOsVersionElement).val() : '';

                        if (selectedCategory === undefined && selectedOsVersion.length > 0) {
                            if (!$J(categoryContainer).find(".os li:first").hasClass('active')) {
                                $J(categoryContainer).find(".os li:first").addClass('active');
                            }
                        }

                        var data = {
                            ProductSupportCategoryId: $J(componentContainer).attr('data-support-category'),
                            ProductId: $J(componentContainer).attr('data-product'),
                            AccessoryId: $J(componentContainer).attr('data-accessory'),
                            pageId: $J(componentContainer).attr('data-page'),
                            ModelId: $J(componentContainer).attr('data-model'),
                            ContentType: '',
                            FileType: '',
                            SelectedCategory: selectedCategory,
                            SelectedOsVersion: selectedOsVersion,
                            Keyword: '',
                            PageIndex: 0,
                            TabId: $J(componentContainer).find('.tabs-container li.active:visible').first().attr("data-tabid"),
                            IsDataSourced: $J(componentContainer).attr('data-isdatasourced')
                        };

                        var resultContainer = $(componentContainer).find('.tabcontent.active .sims-content-container');
                        _simsScope.getSIMSFeed(data, $J(componentContainer), resultContainer);
                    });

                    function searchByKeyword(keyword, componentContainer) {

                        var data = {
                            ProductSupportCategoryId: $J(componentContainer).attr('data-support-category'),
                            ProductId: $J(componentContainer).attr('data-product'),
                            AccessoryId: $J(componentContainer).attr('data-accessory'),
                            PageId: $J(componentContainer).attr('data-page'),
                            ModelId: $J(componentContainer).attr('data-model'),
                            ContentType: $J(componentContainer).find('.tabs-container .desktop li.active').attr('data-content-type'),
                            FileType: '',
                            SelectedCategory: '',
                            SelectedOsVersion: '',
                            Keyword: keyword,
                            PageIndex: 0,
                            TabId: $J(componentContainer).find('.tabs-container li.active:visible').first().attr("data-tabid"),
                            IsDataSourced: $J(componentContainer).attr('data-isdatasourced')
                        };

                        var resultContainer = $(componentContainer).find('.tabcontent.active .sims-content-container');
                        _simsScope.getSIMSFeed(data, $J(componentContainer), resultContainer);
                    }

                    //Search by keyword  desktop and mobile
                    $J('.cf05v2').on('keypress', '.category .sims-search-feed', function (e) {
                        if (e.which === 13) {
                            var keywordInputElement = $J(this);
                            var componentContainer = $J(keywordInputElement).closest('.cf05v2');
                            var tabContentContainer = $J(componentContainer).find('.tabcontent.active');

                            var keyword = $J(keywordInputElement).val();
                            var currentKeyword = $J(keywordInputElement).attr('data-keyword');
                            if (currentKeyword == undefined || currentKeyword !== keyword) {
                                if (keyword.length === 0 && $J(tabContentContainer).find('.category.desktop .os li:first').length > 0) {
                                    $J(tabContentContainer).find('.category.desktop .os li:first').trigger('click');
                                }
                                else if (currentKeyword !== keyword) {
                                    searchByKeyword(keyword, $J(componentContainer));
                                }

                                createOrUpdateStateElement();

                                $J(tabContentContainer).find('.sims-search-feed').attr('data-keyword', keyword);

                                resetFilters(tabContentContainer);
                            }
                        }
                    });

                    $J('.cf05v2').on('click', '.category .sims-search-button', function (e) {

                        createOrUpdateStateElement();

                        var searchButtonElement = $J(this);
                        var componentContainer = $J(searchButtonElement).closest('.cf05v2');
                        var tabContentContainer = $J(componentContainer).find('.tabcontent.active');

                        var keywordInputElement = $J(searchButtonElement).closest('.search-container').find('.sims-search-feed');
                        var currentKeyword = $J(keywordInputElement).attr('data-keyword');
                        var keyword = $J(keywordInputElement).val();

                        if (currentKeyword == undefined || currentKeyword !== keyword) {
                            if ((keyword && keyword.length === 0) && $J(tabContentContainer).find('.category.desktop .os li:first').length > 0) {
                                $J(tabContentContainer).find('.category.desktop .os li:first').trigger('click');
                            }
                            else if (currentKeyword !== keyword) {
                                searchByKeyword(keyword, $J(componentContainer));
                            }

                            $J(tabContentContainer).find('.sims-search-feed').attr('data-keyword', keyword);

                            resetFilters(tabContentContainer);

                        }
                    });

                    $J('.cf05v2').on('click', '.category .sims-search-close-button', function (e) {

                        var resetSearchButton = $J(this);
                        var componentContainer = $J(resetSearchButton).closest('.cf05v2');
                        var tabContentContainer = $J(componentContainer).find('.tabcontent.active');
                        var activeTabButton = $J(componentContainer).find('.tabs-container li.active:visible').first();

                        var keywordInputElement = $J(resetSearchButton).closest('.search-container').find('.sims-search-feed');
                        $J(keywordInputElement).removeAttr('data-keyword');
                        $J(keywordInputElement).val('');

                        var stateElement = $J(tabContentContainer).find('.sims-search-state');
                        if ($J(stateElement).length > 0) {

                            var os = $J(stateElement).attr('data-os-code');
                            var osVersion = $J(stateElement).attr('data-os-version');

                            var data = {
                                ProductSupportCategoryId: $J(componentContainer).attr('data-support-category'),
                                ProductId: $J(componentContainer).attr('data-product'),
                                AccessoryId: $J(componentContainer).attr('data-accessory'),
                                PageId: $J(componentContainer).attr('data-page'),
                                ModelId: $J(componentContainer).attr('data-model'),
                                ContentType: $J(activeTabButton).attr("data-content-type"),
                                FileType: '',
                                SelectedCategory: os !== 'all' ? os : '',
                                SelectedOsVersion: osVersion !== 'all' ? osVersion : '',
                                Keyword: '',
                                PageIndex: 0,
                                TabId: $J(activeTabButton).attr("data-tabid"),
                                IsDataSourced: $J(componentContainer).attr('data-isdatasourced')
                            };

                            $J(tabContentContainer).find(".category.desktop .os li.active").removeClass('active');
                            if (os === undefined || os === 'all') {
                                $J(tabContentContainer).find(".category.desktop .os li:first").addClass('active');
                            }
                            else {
                                $J(tabContentContainer).find(".category.desktop .os li[data-os-code='" + os + "']").addClass('active');
                            }

                            $J(tabContentContainer).find(".category.desktop .download-os-version").val(osVersion);

                            $J(tabContentContainer).find(".category.mobile .download-os-type option[selected]").removeAttr('selected');
                            $J(tabContentContainer).find(".category.mobile .download-os-type option[value='" + os + "']").attr('selected', '');
                            $J(tabContentContainer).find(".category.mobile .download-os-type").val(os);

                            $J(tabContentContainer).find(".category.mobile .download-os-version option[selected]").removeAttr('selected');
                            $J(tabContentContainer).find(".category.mobile .download-os-version option[value='" + osVersion + "']").attr('selected', '');
                            $J(tabContentContainer).find(".category.mobile .download-os-version").val(osVersion);

                            var resultContainer = $(componentContainer).find('.tabcontent.active .sims-content-container');
                            _simsScope.getSIMSFeed(data, $J(componentContainer), resultContainer);
                        }
                        else {
                            if ($J(tabContentContainer).hasClass('tab1')) {
                                resetFilters(tabContentContainer);
                                autoDetectOsAndStartFetchTheData();
                            }
                            else {
                                searchByKeyword('', $J(componentContainer));
                            }
                        }
                    });

                    autoDetectOsAndStartFetchTheData();

                }
            },

            initSIMSFeedPaging: function () {
                if ($J('.cf05v2 .paging').length > 0) {

                    $J('.cf05v2').on('click', '.paging li', function () {
                        var pageElement = $J(this);

                        $J(pageElement).closest('.paging').find('li.active').removeClass('active');

                        var componentContainer = $J(pageElement).closest('.cf05v2');
                        var tabContentContainer = $J(componentContainer).find('.tabcontent.active');
                        var keywordElement = canonHelper.isMobile() ? $J(tabContentContainer).find('.mobile .sims-search-feed') : $J(tabContentContainer).find('.desktop .sims-search-feed');
                        var keyword = $J(keywordElement).val().length > 0 ? $J(keywordElement).val() : '';

                        var selectedCategoryElement = $(tabContentContainer).find('.os li.active');
                        var selectedCategory = selectedCategoryElement != undefined && selectedCategoryElement.length > 0 ? $J(selectedCategoryElement).attr('data-os-code') : '';
                        var selectedOsVersionElement = $(tabContentContainer).find('select.download-os-version');
                        var selectedOsVersion = $J(selectedOsVersionElement).val() !== 'all' ? $J(selectedOsVersionElement).val() : '';

                        var data = {
                            ProductSupportCategoryId: $J(componentContainer).attr('data-support-category'),
                            ProductId: $J(componentContainer).attr('data-product'),
                            AccessoryId: $J(componentContainer).attr('data-accessory'),
                            PageId: $J(componentContainer).attr('data-page'),
                            ModelId: $J(componentContainer).attr('data-model'),
                            ContentType: $J(pageElement).attr('data-contenttype'),
                            FileType: $J(pageElement).attr('data-filetype'),
                            SelectedCategory: keyword.length > 0 ? '' : selectedCategory,
                            SelectedOsVersion: keyword.length > 0 ? '' : selectedOsVersion,
                            Keyword: keyword,
                            PageIndex: $J(pageElement).attr('data-page'),
                            IsDataSourced: $J(componentContainer).attr('data-isdatasourced'),
                            GroupId: $J(pageElement).attr('data-groupId')
                        };

                        var resultContainer = $(pageElement).closest('.paging').siblings('.sims-content');

                        _simsScope.getSIMSFeedPerPage(data, componentContainer, resultContainer);

                        $J(pageElement).addClass('active');
                    });

                }
            },

            getSIMSFeedPerPage: function (postData, componentContainer, resultContainer) {
                canonHelper.showSpinner();
                var data = canonHelper.addAntiForgeryToken(postData);
                var post = $.post('/content-tile/productsupport/getsimsfeedperpage', data);

                var template = $J(componentContainer).find('.sims-content-template').html();

                post.done(function (data) {

                    if (data.SIMSContent) {
                        var result = Mustache.to_html(template, data);
                        $(resultContainer).html(result);
                    }

                    canonHelper.hideSpinner();
                });

                post.fail(function () {
                    canonHelper.hideSpinner();
                });
            },

            getSIMSFeed: function (postData, componentContainer, resultContainer) {
                canonHelper.showSpinner();
                var data = canonHelper.addAntiForgeryToken(postData);
                var post = $.post('/content-tile/productsupport/getsimsfeed', data);

                var template = $J(componentContainer).find('.sims-content-full-template').html();

                post.done(function (data) {

                    if (data.TabItems) {
                        if (data.TabItems.length > 0) {
                            var result = Mustache.to_html(template, data);
                            $J(resultContainer).html(result);
                        }
                        else {
                            $J(resultContainer).html($J('.no-result-found-template').html());
                        }
                    }

                    canonHelper.hideSpinner();
                });

                post.fail(function () {
                    canonHelper.hideSpinner();
                });
            },

            initSIMSContentPageEvents: function () {
                function showHideSurvey(surveydiv, surveymsg) {
                    $(surveydiv).hide();
                    $(surveymsg).html("<strong>Thank you for the feedback.</strong>").show();
                }

                $J(".btn-downloadDriver").removeAttr("href").attr("disabled", true);

                $org = $J(".cp23 .cp04 a.btn-downloadDriver");
                $clone = $J(".cp23 .cp04 a.btn-downloadDriver").clone().attr("disabled", false).attr("href", $(".cp23 .checkAgree").attr("data-targeturl")).css("display", "none");
                $J(".cp23 .cp04").append($clone);
                $J(".cp23 .checkAgree").on("click", function () {
                    $this = $(this);
                    if ($this[0].checked) {
                        $org.css("display", "none");
                        $clone.css("display", "inline-block");
                    } else {
                        $clone.css("display", "none");
                        $org.css("display", "inline-block");
                    }
                });

                $J('.btn_SubmitSurvey').on('click', function () {
                    var surveyId = $(this).data("surveyid");
                    var contentid = $(this).data("sims-contentid");
                    var surveydiv = $(this).parents("div .faq_survery_" + contentid);
                    var surveymsg = $("div .faq_survey_msg_" + contentid);
                    var memberId = $(this).data("memberid");
                    var surveyValue = $("div .faq_survery_" + contentid + " input[name=surveyOption]:checked");
                    var surveysUri = $(this).data("surveyuri");
                    if ($(surveyValue).length) {
                        var PostSurveyRequest = { SurveyId: surveyId, ContentId: contentid, MemberId: memberId, SurveyValue: $(surveyValue).val() };

                        var ajaxUrl = surveysUri + "/" + surveyId;
                        $.ajax({
                            type: 'POST',
                            url: ajaxUrl,
                            data: JSON.stringify(PostSurveyRequest),
                            contentType: 'application/json',
                            beforeSend: function (xhr) {
                                xhr.setRequestHeader('Source', 'canon');
                            },
                            error: function (xhr, errorType, exception) {
                                var responseText = "There is some exception, please contact support.";
                                alert(responseText);
                            }
                        }).done(function (response) {
                            if (response.status === "OK") {
                                showHideSurvey($(surveydiv), $(surveymsg));
                            }
                            else {
                                alert(response.error);
                            }
                        });
                    }
                    else {
                        alert("Please choose any one of above options.");
                    }
                });
            }
        };

        return _simsScope;

    })();

    $J(document).ready(function () {
        if (canonHelper !== undefined) {
            sims.init();
        }
    });
})(jQuery);;
(function ($J) {
    var news = (function () {
        var _newsScope = {
            init: function () {
                this.initNewsFilter();
                this.initNewsFilterByKeyword();
                this.initNewsFilterLoadMore();
            },

            initNewsFilter: function () {
                $J('.filter-toggle').on('click', function () {
                    var filterToggleButton = $J(this);
                    var newsFilterContainer = $J(filterToggleButton).closest('.nv15').find('.news-filter-container');
                    $J(newsFilterContainer).toggleClass('active');
                });

                //Desktop
                $J('.news-filter-key').on('click', function (el) {
                    el.preventDefault();
                    var newsFilterKeyElement = $J(this);

                    if (!$J(newsFilterKeyElement).hasClass('under')) {
                        var selectedFilter = $J(newsFilterKeyElement).attr('data-filter-key');
                        var newsFilterContainer = $J(newsFilterKeyElement).closest('.nv15').find('.news-filter-container');

                        $J(newsFilterContainer).attr('data-selected-filter', selectedFilter);

                        var filterContainer = $J(newsFilterKeyElement).closest('.filter-container');
                        $J(filterContainer).find('.filter-toggle').text($J(newsFilterKeyElement).text());

                        $J(newsFilterKeyElement).closest('ul').find('.news-filter-key.under').removeClass('under');

                        var sourceId = filterContainer.siblings('.news-content-feed').attr('data-source');
                        var tileContainer = filterContainer.siblings('.news-content-feed').find(".tile-container");

                        if ($J(filterContainer).find('.news-feed-keyword').length > 0) {
                            $J(filterContainer).find('.news-feed-keyword').val('');
                            $J(filterContainer).find('.news-feed-keyword').attr('data-keyword', '');
                        }

                        $J(filterContainer).find('.mobile option').each(function () {
                            $J(this).removeAttr('selected');

                            if ($J(this).attr('data-filter-key') === selectedFilter) {
                                $J(this).attr('selected', '');
                                $J(this).parent('select').val(selectedFilter);
                            }
                        });

                        var postData = {
                            CurrentNewsLandingPage: sourceId,
                            PageIndex: 0,
                            SelectedFilter: selectedFilter,
                            Keyword: ''
                        };

                        _newsScope.callNewsFeed(postData, tileContainer, true);
                        var query = window.location.search.substring(1);
                        if (query.length) {
                            if (window.history != undefined && window.history.pushState != undefined) {
                                window.history.pushState({}, '', window.location.pathname);
                            }
                        }

                        $J(newsFilterKeyElement).addClass('under');
                        $J(newsFilterContainer).toggleClass('active');
                    }
                });

                //mobile
                $J(".news-filter-dropdown").on("change", function (e) {

                    var selectedValue = $J(this).find(':selected');
                    var selectedFilter = selectedValue.attr('data-filter-key');

                    if ($J(this).closest('.mobile').css('display') !== 'none') {
                        $J(this).closest('.nv15.filter-container').find('li').each(function () {
                            if ($J(this).attr('data-filter') === selectedFilter) {
                                $J(this).trigger('click');
                            }
                        });
                    }
                });
            },

            initNewsFilterByKeyword: function () {
                $J('.news-feed-keyword').keypress(function (e) {
                    if (e.which == 13) {
                        var keyword = $J(this).val();
                        var currentKeyword = $J(this).attr('data-keyword');
                        if (currentKeyword == undefined || currentKeyword !== keyword) {
                            searchByKeyword(keyword, $J(this));
                            $J(this).attr('data-keyword', keyword);
                        }
                        var query = window.location.search.substring(1);
                        if (query.length) {
                            if (window.history != undefined && window.history.pushState != undefined) {
                                window.history.pushState({}, '', window.location.pathname);
                            }
                        }
                    }
                });

                $J('.news-feed-keyword-btn').on('click', function () {
                    var keyword = $J(this).parent().find(".news-feed-keyword").val();
                    var currentKeyword = $J(this).parent().find(".news-feed-keyword").attr('data-keyword');
                    if (currentKeyword == undefined || currentKeyword !== keyword) {
                        $J(this).parent().find(".news-feed-keyword").attr('data-keyword', keyword);
                        searchByKeyword(keyword, $J(this));
                    }
                });

                function searchByKeyword(keyword, el) {

                    var filterContainer = $J(el).closest('.filter-container');

                    var sourceId = filterContainer.siblings(".news-content-feed").attr('data-source');
                    var tileContainer = filterContainer.siblings(".news-content-feed").find(".tile-container");

                    var selectedFilter = $J(el).closest('.filter-container').find('.news-filter-container').attr('data-selected-filter');
                    if (selectedFilter == undefined) {
                        selectedFilter = '';
                    }

                    var postData = {
                        CurrentNewsLandingPage: sourceId,
                        PageIndex: 0,
                        SelectedFilter: selectedFilter,
                        Keyword: keyword
                    };

                    _newsScope.callNewsFeed(postData, tileContainer, true);
                }
            },

            initNewsFilterLoadMore: function () {
                $J('.news-load-more-feed a').on('click', function (e) {
                    e.preventDefault();

                    var keyword = '';
                    var selectedFilter = $J(this).closest('.news-content-feed').siblings('.filter-container').find('.news-filter-container').attr('data-selected-filter');
                    $J(this).closest('.news-filter-container').attr('data-selected-filter', selectedFilter);
                    var filterContainer = $J(this).closest('.filter-container');

                    var sourceId = $J(this).closest('.news-content-feed').attr('data-source');
                    var tileContainer = $J(this).closest('.news-content-feed').find(".tile-container");

                    if ($J(filterContainer).find('.news-feed-keyword').length > 0) {
                        if ($J(filterContainer).find('.news-feed-keyword').val()) {
                            keyword = $J(filterContainer).find('.news-feed-keyword').val();
                        }
                    }

                    var currentPageIndex = $J(this).attr("data-current-page");
                    var pageToRender = parseInt(currentPageIndex) + 1;

                    var postData = {
                        CurrentNewsLandingPage: sourceId,
                        PageIndex: pageToRender,
                        SelectedFilter: selectedFilter,
                        Keyword: keyword
                    };

                    $J(this).blur();
                    _newsScope.callNewsFeed(postData, tileContainer, false);
                });
            },

            callNewsFeed: function (postData, tileContainer, replaceHtml) {
                canonHelper.showSpinner();

                var data = canonHelper.addAntiForgeryToken(postData);
                var post = $J.post('/content-tile/news/getnewslistingfeed', data);

                post.done(function (data) {
                    var template;
                    // Try loading the external template files
                    $.when($.get("/mustachetemplates/content-listing-feed.html", function (source) { template = source; }))
                        .then(function () {
                            var noDataFoundEl = $J(tileContainer).parent().find(".news-feed-empty");
                            var loadMoreEl = $J(tileContainer).parent().find(".news-load-more-feed a");
                            var loadMoreContainerEl = $J(tileContainer).parent().find(".news-load-more-feed");

                            if (data.ContentListingFeedSkinnyTiles && data.ContentListingFeedSkinnyTiles.length > 0) {
                                var result = Mustache.to_html(template, data);
                                noDataFoundEl.slideUp(500);

                                if (replaceHtml) {
                                    $J(tileContainer).html(result);
                                } else {
                                    $J(tileContainer).append(result);
                                }

                                $J(tileContainer).slideDown(500);
                                canonHelper.constructVideoElement();
                                canonHelper.tileMarginFix($J(tileContainer));

                            }
                            else {
                                if (noDataFoundEl.hasClass("hide--me")) {
                                    noDataFoundEl.removeClass("hide--me");
                                }

                                $J(tileContainer).slideUp(500);
                                noDataFoundEl.slideDown(500);
                            }

                            if (data && data.IsNextPageAvailable) {
                                var loadMoreText = "<span>Load more " + data.TilesTypeForLoadMore + "</span><br>" + "(" + data.NextItemToDisplayed + ") " + data.TilesCounterForLoadMore + " left";
                                $J(loadMoreEl).html(loadMoreText);
                                $J(loadMoreEl).attr("data-current-page", data.CurrentPageIndex);
                                $J(loadMoreContainerEl).removeClass('hide--me');
                            } else {
                                if (!loadMoreContainerEl.hasClass('hide--me')) {
                                    loadMoreContainerEl.addClass('hide--me');
                                }
                            }

                            canonHelper.hideSpinner();

                        },
                        function () {
                            // templates not loaded
                            var templateError = 'Error: Could not load plugin templates. Check the paths and ensure they have been uploaded. Paths will be wrong if you do not run this from a web server.'; console.log(templateError);
                            canonHelper.hideSpinner();
                        });
                });

                post.fail(function () {
                    canonHelper.hideSpinner();
                });

                post.always(function () {
                    //$J('.load-more-feed button').prop('disabled', false).removeClass('loading');
                });
            }
        };

        return _newsScope;

    })();

    $J(document).ready(function () {
        if (canonHelper !== undefined) {
            news.init();
        }
    });
})(jQuery);;
(function ($J) {
    var news = (function () {
        var _newsScope = {
            init: function () {
                this.initNewsFilter();
                this.initNewsFilterByKeyword();
                this.initNewsFilterLoadMore();
            },

            initNewsFilter: function () {
                $J('.filter-toggle').on('click', function () {
                    var filterToggleButton = $J(this);
                    var newsFilterContainer = $J(filterToggleButton).closest('.nv15').find('.edge-filter-container');
                    $J(newsFilterContainer).toggleClass('active');
                });

                //Desktop
                $J('.edge-filter-key').on('click', function (el) {
                    el.preventDefault();
                    var newsFilterKeyElement = $J(this);

                    if (!$J(newsFilterKeyElement).hasClass('under')) {
                        var selectedFilter = $J(newsFilterKeyElement).attr('data-filter-key');
                        var newsFilterContainer = $J(newsFilterKeyElement).closest('.nv15').find('.edge-filter-container');

                        $J(newsFilterContainer).attr('data-selected-filter', selectedFilter);

                        var filterContainer = $J(newsFilterKeyElement).closest('.filter-container');
                        $J(filterContainer).find('.filter-toggle').text($J(newsFilterKeyElement).text());

                        $J(newsFilterKeyElement).closest('ul').find('.edge-filter-key.under').removeClass('under');

                        var sourceId = filterContainer.siblings('.edge-content-feed').attr('data-source');
                        var tileContainer = filterContainer.siblings('.edge-content-feed').find(".tile-container");

                        if ($J(filterContainer).find('.edge-feed-keyword').length > 0) {
                            $J(filterContainer).find('.edge-feed-keyword').val('');
                            $J(filterContainer).find('.edge-feed-keyword').attr('data-keyword', '');
                        }

                        $J(filterContainer).find('.mobile option').each(function () {
                            $J(this).removeAttr('selected');

                            if ($J(this).attr('data-filter-key') === selectedFilter) {
                                $J(this).attr('selected', '');
                                $J(this).parent('select').val(selectedFilter);
                            }
                        });

                        var postData = {
                            DataSource: sourceId,
                            PageIndex: 0,
                            SelectedFilter: selectedFilter,
                            Keyword: ''
                        };

                        _newsScope.callNewsFeed(postData, tileContainer, true);
                        var query = window.location.search.substring(1);
                        if (query.length) {
                            if (window.history != undefined && window.history.pushState != undefined) {
                                window.history.pushState({}, '', window.location.pathname);
                            }
                        }

                        $J(newsFilterKeyElement).addClass('under');
                        $J(newsFilterContainer).toggleClass('active');
                    }
                });

                //mobile
                $J(".news-filter-dropdown").on("change", function (e) {

                    var selectedValue = $J(this).find(':selected');
                    var selectedFilter = selectedValue.attr('data-filter-key');

                    if ($J(this).closest('.mobile').css('display') !== 'none') {
                        $J(this).closest('.nv15.filter-container').find('li').each(function () {
                            if ($J(this).attr('data-filter') === selectedFilter) {
                                $J(this).trigger('click');
                            }
                        });
                    }
                });
            },

            initNewsFilterByKeyword: function () {
                $J('.edge-feed-keyword').keypress(function (e) {
                    if (e.which == 13) {
                        var keyword = $J(this).val();
                        var currentKeyword = $J(this).attr('data-keyword');
                        if (currentKeyword == undefined || currentKeyword !== keyword) {
                            searchByKeyword(keyword, $J(this));
                            $J(this).attr('data-keyword', keyword);
                        }
                        var query = window.location.search.substring(1);
                        if (query.length) {
                            if (window.history != undefined && window.history.pushState != undefined) {
                                window.history.pushState({}, '', window.location.pathname);
                            }
                        }
                    }
                });

                $J('.edge-feed-keyword-btn').on('click', function () {
                    var keyword = $J(this).parent().find(".edge-feed-keyword").val();
                    var currentKeyword = $J(this).parent().find(".edge-feed-keyword").attr('data-keyword');
                    if (currentKeyword == undefined || currentKeyword !== keyword) {
                        $J(this).parent().find(".edge-feed-keyword").attr('data-keyword', keyword);
                        searchByKeyword(keyword, $J(this));
                    }
                });

                function searchByKeyword(keyword, el) {

                    var filterContainer = $J(el).closest('.filter-container');

                    var sourceId = filterContainer.siblings(".edge-content-feed").attr('data-source');
                    var tileContainer = filterContainer.siblings(".edge-content-feed").find(".tile-container");

                    var selectedFilter = $J(el).closest('.filter-container').find('.edge-filter-container').attr('data-selected-filter');
                    if (selectedFilter == undefined) {
                        selectedFilter = '';
                    }

                    var postData = {
                        DataSource: sourceId,
                        PageIndex: 0,
                        SelectedFilter: selectedFilter,
                        Keyword: keyword
                    };

                    _newsScope.callNewsFeed(postData, tileContainer, true);
                }
            },

            initNewsFilterLoadMore: function () {
                $J('.edge-load-more-feed a').on('click', function (e) {
                    e.preventDefault();

                    var keyword = '';
                    var selectedFilter = $J(this).closest('.edge-content-feed').siblings('.filter-container').find('.edge-filter-container').attr('data-selected-filter');
                    $J(this).closest('.edge-filter-container').attr('data-selected-filter', selectedFilter);
                    var filterContainer = $J(this).closest('.filter-container');

                    var sourceId = $J(this).closest('.edge-content-feed').attr('data-source');
                    var tileContainer = $J(this).closest('.edge-content-feed').find(".tile-container");

                    if ($J(filterContainer).find('.edge-feed-keyword').length > 0) {
                        if ($J(filterContainer).find('.edge-feed-keyword').val()) {
                            keyword = $J(filterContainer).find('.edge-feed-keyword').val();
                        }
                    }

                    var currentPageIndex = $J(this).attr("data-current-page");
                    var pageToRender = parseInt(currentPageIndex) + 1;

                    var postData = {
                        DataSource: sourceId,
                        PageIndex: pageToRender,
                        SelectedFilter: selectedFilter,
                        Keyword: keyword,
                        IsLoadMore: true
                    };

                    $J(this).blur();
                    _newsScope.callNewsFeed(postData, tileContainer, false);
                });
            },

            callNewsFeed: function (postData, tileContainer, replaceHtml) {
                canonHelper.showSpinner();

                var data = canonHelper.addAntiForgeryToken(postData);
                var post = $J.post('/content-tile/edge/getcontentfeedfarm', data);

                post.done(function (data) {
                    var template;
                    // Try loading the external template files
                    $.when($.get("/mustachetemplates/content-listing-feed.html", function (source) { template = source; }))
                        .then(function () {
                            var noDataFoundEl = $J(tileContainer).parent().find(".news-feed-empty");
                            var loadMoreEl = $J(tileContainer).parent().find(".edge-load-more-feed a");
                            var loadMoreContainerEl = $J(tileContainer).parent().find(".edge-load-more-feed");

                            if (data.ContentListingFeedSkinnyTiles && data.ContentListingFeedSkinnyTiles.length > 0) {
                                var result = Mustache.to_html(template, data);
                                noDataFoundEl.slideUp(500);

                                if (replaceHtml) {
                                    $J(tileContainer).html(result);
                                } else {
                                    $J(tileContainer).append(result);
                                }

                                $J(tileContainer).slideDown(500);
                                canonHelper.constructVideoElement();
                                canonHelper.tileMarginFix($J(tileContainer));

                            }
                            else {
                                if (noDataFoundEl.hasClass("hide--me")) {
                                    noDataFoundEl.removeClass("hide--me");
                                }

                                $J(tileContainer).slideUp(500);
                                noDataFoundEl.slideDown(500);
                            }

                            if (data && data.IsNextPageAvailable) {
                                var loadMoreText = "<span>Load more</span><br />" + "(" + data.NextItemToDisplayed + " items left)";
                                $J(loadMoreEl).html(loadMoreText);
                                $J(loadMoreEl).attr("data-current-page", data.CurrentPageIndex);
                                $J(loadMoreContainerEl).removeClass('hide--me');
                            } else {
                                if (!loadMoreContainerEl.hasClass('hide--me')) {
                                    loadMoreContainerEl.addClass('hide--me');
                                }
                            }

                            canonHelper.hideSpinner();

                        },
                        function () {
                            // templates not loaded
                            var templateError = 'Error: Could not load plugin templates. Check the paths and ensure they have been uploaded. Paths will be wrong if you do not run this from a web server.'; console.log(templateError);
                            canonHelper.hideSpinner();
                        });
                });

                post.fail(function () {
                    canonHelper.hideSpinner();
                });

                post.always(function () {
                    //$J('.load-more-feed button').prop('disabled', false).removeClass('loading');
                });
            }
        };

        return _newsScope;

    })();

    $J(document).ready(function () {
        if (canonHelper !== undefined) {
            news.init();
        }
    });
})(jQuery);;
